Coverage Report

Created: 2024-04-28 01:18

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90.6 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/04/18 (1.90.6) - treeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
442
                           - old: TreeNode("##Hidden"); SameLine(); Text("Hello");     // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
443
                           - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
444
                         with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
445
                         You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
446
                         (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
447
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
448
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
449
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
450
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
451
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
452
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
453
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
454
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
455
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
456
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
457
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
458
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
459
                           - old: BeginChild("Name", size, true)
460
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
461
                           - old: BeginChild("Name", size, false)
462
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
463
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
464
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
465
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
466
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
467
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
468
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
469
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
470
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
471
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
472
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
473
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
474
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
475
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
476
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
477
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
478
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
479
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
480
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
481
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
482
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
483
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
484
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
485
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
486
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
487
                           - ListBoxFooter()  -> use EndListBox()
488
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
489
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
490
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
491
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
492
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
493
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
494
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
495
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
496
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
497
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
498
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
499
                         it has been frequently requested by people to use our own. We had an opt-in define which was
500
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
501
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
502
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
503
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
504
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
505
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
506
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
507
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
508
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
509
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
510
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
511
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
512
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
513
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
514
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
515
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
516
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
517
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
518
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
519
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
520
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
521
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
522
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
523
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
524
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
525
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
526
                         - previously this would make the window content size ~200x200:
527
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
528
                         - instead, please submit an item:
529
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
530
                         - alternative:
531
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
532
                         - content size is now only extended when submitting an item!
533
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
534
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
535
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
536
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
537
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
538
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
539
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
540
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
541
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
542
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
543
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
544
                        - Official backends from 1.87+                  -> no issue.
545
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
546
                        - Custom backends not writing to io.NavInputs[] -> no issue.
547
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
548
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
549
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
550
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
551
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
552
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
553
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
554
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
555
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
556
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
557
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
558
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
559
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
560
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
561
                       read https://github.com/ocornut/imgui/issues/4921 for details.
562
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
563
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
564
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
565
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
566
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
567
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
568
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
569
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
570
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
571
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
572
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
573
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
574
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
575
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
576
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
577
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
578
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
579
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
580
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
581
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
582
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
583
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
584
                        - if you are using official backends from the source tree: you have nothing to do.
585
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
586
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
587
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
588
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
589
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
590
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
591
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
592
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
593
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
594
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
595
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
596
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
597
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
598
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
599
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
600
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
601
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
602
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
603
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
604
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
605
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
606
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
607
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
608
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
609
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
610
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
611
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
612
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
613
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
614
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
615
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
616
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
617
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
618
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
619
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
620
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
621
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
622
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
623
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
624
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
625
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
626
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
627
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
628
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
629
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
630
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
631
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
632
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
633
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
634
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
635
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
636
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
637
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
638
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
639
                       - if you omitted the 'power' parameter (likely!), you are not affected.
640
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
641
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
642
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
643
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
644
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
645
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
646
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
647
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
648
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
649
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
650
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
651
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
652
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
653
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
654
                       - ShowTestWindow()                    -> use ShowDemoWindow()
655
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
656
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
657
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
658
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
659
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
660
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
661
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
662
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
663
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
664
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
665
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
666
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
667
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
668
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
669
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
670
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
671
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
672
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
673
                       - ImFont::Glyph                       -> use ImFontGlyph
674
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
675
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
676
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
677
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
678
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
679
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
680
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
681
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
682
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
683
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
684
                       Please reach out if you are affected.
685
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
686
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
687
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
688
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
689
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
690
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
691
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
692
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
693
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
694
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
695
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
696
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
697
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
698
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
699
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
700
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
701
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
702
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
703
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
704
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
705
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
706
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
707
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
708
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
709
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
710
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
711
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
712
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
713
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
714
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
715
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
716
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
717
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
718
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
719
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
720
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
721
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
722
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
723
                       consistent with other functions. Kept redirection functions (will obsolete).
724
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
725
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
726
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
727
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
728
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
729
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
730
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
731
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
732
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
733
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
734
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
735
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
736
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
737
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
738
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
739
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
740
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
741
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
742
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
743
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
744
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
745
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
746
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
747
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
748
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
749
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
750
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
751
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
752
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
753
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
754
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
755
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
756
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
757
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
758
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
759
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
760
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
761
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
762
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
763
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
764
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
765
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
766
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
767
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
768
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
769
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
770
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
771
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
772
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
773
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
774
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
775
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
776
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
777
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
778
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
779
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
780
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
781
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
782
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
783
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
784
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
785
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
786
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
787
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
788
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
789
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
790
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
791
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
792
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
793
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
794
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
795
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
796
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
797
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
798
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
799
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
800
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
801
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
802
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
803
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
804
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
805
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
806
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
807
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
808
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
809
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
810
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
811
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
812
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
813
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
814
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
815
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
816
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
817
                     - the signature of the io.RenderDrawListsFn handler has changed!
818
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
819
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
820
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
821
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
822
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
823
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
824
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
825
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
826
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
827
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
828
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
829
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
830
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
831
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
832
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
833
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
834
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
835
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
836
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
837
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
838
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
839
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
840
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
841
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
842
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
843
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
844
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
845
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
846
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
847
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
848
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
849
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
850
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
851
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
852
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
853
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
854
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
855
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
856
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
857
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
858
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
859
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
860
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
861
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
862
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
863
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
864
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
865
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
866
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
867
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
868
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
869
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
870
871
872
 FREQUENTLY ASKED QUESTIONS (FAQ)
873
 ================================
874
875
 Read all answers online:
876
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
877
 Read all answers locally (with a text editor or ideally a Markdown viewer):
878
   docs/FAQ.md
879
 Some answers are copied down here to facilitate searching in code.
880
881
 Q&A: Basics
882
 ===========
883
884
 Q: Where is the documentation?
885
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
886
    - Run the examples/ applications and explore them.
887
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
888
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
889
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
890
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
891
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
892
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
893
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
894
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
895
    - Your programming IDE is your friend, find the type or function declaration to find comments
896
      associated with it.
897
898
 Q: What is this library called?
899
 Q: Which version should I get?
900
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
901
 >> See https://www.dearimgui.com/faq for details.
902
903
 Q&A: Integration
904
 ================
905
906
 Q: How to get started?
907
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
908
909
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
910
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
911
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
912
913
 Q. How can I enable keyboard or gamepad controls?
914
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
915
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
916
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
917
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
918
 >> See https://www.dearimgui.com/faq
919
920
 Q&A: Usage
921
 ----------
922
923
 Q: About the ID Stack system..
924
   - Why is my widget not reacting when I click on it?
925
   - How can I have widgets with an empty label?
926
   - How can I have multiple widgets with the same label?
927
   - How can I have multiple windows with the same label?
928
 Q: How can I display an image? What is ImTextureID, how does it work?
929
 Q: How can I use my own math types instead of ImVec2?
930
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
931
 Q: How can I display custom shapes? (using low-level ImDrawList API)
932
 >> See https://www.dearimgui.com/faq
933
934
 Q&A: Fonts, Text
935
 ================
936
937
 Q: How should I handle DPI in my application?
938
 Q: How can I load a different font than the default?
939
 Q: How can I easily use icons in my application?
940
 Q: How can I load multiple fonts?
941
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
942
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
943
944
 Q&A: Concerns
945
 =============
946
947
 Q: Who uses Dear ImGui?
948
 Q: Can you create elaborate/serious tools with Dear ImGui?
949
 Q: Can you reskin the look of Dear ImGui?
950
 Q: Why using C++ (as opposed to C)?
951
 >> See https://www.dearimgui.com/faq
952
953
 Q&A: Community
954
 ==============
955
956
 Q: How can I help?
957
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
958
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
959
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
960
      >>> See https://github.com/ocornut/imgui/wiki/Funding
961
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
962
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
963
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
964
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
965
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
966
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
967
968
*/
969
970
//-------------------------------------------------------------------------
971
// [SECTION] INCLUDES
972
//-------------------------------------------------------------------------
973
974
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
975
#define _CRT_SECURE_NO_WARNINGS
976
#endif
977
978
#ifndef IMGUI_DEFINE_MATH_OPERATORS
979
#define IMGUI_DEFINE_MATH_OPERATORS
980
#endif
981
982
#include "imgui.h"
983
#ifndef IMGUI_DISABLE
984
#include "imgui_internal.h"
985
986
// System includes
987
#include <stdio.h>      // vsnprintf, sscanf, printf
988
#include <stdint.h>     // intptr_t
989
990
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
991
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
992
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
993
#endif
994
995
// [Windows] OS specific includes (optional)
996
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
997
#define IMGUI_DISABLE_WIN32_FUNCTIONS
998
#endif
999
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1000
#ifndef WIN32_LEAN_AND_MEAN
1001
#define WIN32_LEAN_AND_MEAN
1002
#endif
1003
#ifndef NOMINMAX
1004
#define NOMINMAX
1005
#endif
1006
#ifndef __MINGW32__
1007
#include <Windows.h>        // _wfopen, OpenClipboard
1008
#else
1009
#include <windows.h>
1010
#endif
1011
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
1012
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1013
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1014
#endif
1015
#endif
1016
1017
// [Apple] OS specific includes
1018
#if defined(__APPLE__)
1019
#include <TargetConditionals.h>
1020
#endif
1021
1022
// Visual Studio warnings
1023
#ifdef _MSC_VER
1024
#pragma warning (disable: 4127)             // condition expression is constant
1025
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1026
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1027
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1028
#endif
1029
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1030
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1031
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1032
#endif
1033
1034
// Clang/GCC warnings with -Weverything
1035
#if defined(__clang__)
1036
#if __has_warning("-Wunknown-warning-option")
1037
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1038
#endif
1039
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1040
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1041
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1042
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1043
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1044
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1045
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1046
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1047
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1048
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1049
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1050
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1051
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
1052
#elif defined(__GNUC__)
1053
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1054
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1055
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1056
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1057
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1058
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1059
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1060
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1061
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1062
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1063
#endif
1064
1065
// Debug options
1066
0
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1067
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1068
1069
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1070
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1071
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1072
1073
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1074
1075
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1076
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1077
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1078
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1079
1080
// Tooltip offset
1081
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1082
1083
// Docking
1084
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1085
1086
//-------------------------------------------------------------------------
1087
// [SECTION] FORWARD DECLARATIONS
1088
//-------------------------------------------------------------------------
1089
1090
static void             SetCurrentWindow(ImGuiWindow* window);
1091
static void             FindHoveredWindow();
1092
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1093
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1094
1095
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1096
1097
// Settings
1098
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1099
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1100
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1101
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1102
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1103
1104
// Platform Dependents default implementation for IO functions
1105
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1106
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1107
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1108
1109
namespace ImGui
1110
{
1111
// Navigation
1112
static void             NavUpdate();
1113
static void             NavUpdateWindowing();
1114
static void             NavUpdateWindowingOverlay();
1115
static void             NavUpdateCancelRequest();
1116
static void             NavUpdateCreateMoveRequest();
1117
static void             NavUpdateCreateTabbingRequest();
1118
static float            NavUpdatePageUpPageDown();
1119
static inline void      NavUpdateAnyRequestFlag();
1120
static void             NavUpdateCreateWrappingRequest();
1121
static void             NavEndFrame();
1122
static bool             NavScoreItem(ImGuiNavItemData* result);
1123
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1124
static void             NavProcessItem();
1125
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1126
static ImVec2           NavCalcPreferredRefPos();
1127
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1128
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1129
static void             NavRestoreLayer(ImGuiNavLayer layer);
1130
static int              FindWindowFocusIndex(ImGuiWindow* window);
1131
1132
// Error Checking and Debug Tools
1133
static void             ErrorCheckNewFrameSanityChecks();
1134
static void             ErrorCheckEndFrameSanityChecks();
1135
static void             UpdateDebugToolItemPicker();
1136
static void             UpdateDebugToolStackQueries();
1137
static void             UpdateDebugToolFlashStyleColor();
1138
1139
// Inputs
1140
static void             UpdateKeyboardInputs();
1141
static void             UpdateMouseInputs();
1142
static void             UpdateMouseWheel();
1143
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1144
1145
// Misc
1146
static void             UpdateSettings();
1147
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1148
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1149
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1150
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1151
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1152
static void             RenderDimmedBackgrounds();
1153
static void             SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1154
1155
// Viewports
1156
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1157
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1158
static void             DestroyViewport(ImGuiViewportP* viewport);
1159
static void             UpdateViewportsNewFrame();
1160
static void             UpdateViewportsEndFrame();
1161
static void             WindowSelectViewport(ImGuiWindow* window);
1162
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1163
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1164
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1165
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1166
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1167
static int              FindPlatformMonitorForRect(const ImRect& r);
1168
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1169
1170
}
1171
1172
//-----------------------------------------------------------------------------
1173
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1174
//-----------------------------------------------------------------------------
1175
1176
// DLL users:
1177
// - Heaps and globals are not shared across DLL boundaries!
1178
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1179
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1180
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1181
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1182
1183
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1184
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1185
//   Change to a different context by calling ImGui::SetCurrentContext().
1186
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1187
//   If you want thread-safety to allow N threads to access N different contexts:
1188
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1189
//         struct ImGuiContext;
1190
//         extern thread_local ImGuiContext* MyImGuiTLS;
1191
//         #define GImGui MyImGuiTLS
1192
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1193
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1194
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1195
// - DLL users: read comments above.
1196
#ifndef GImGui
1197
ImGuiContext*   GImGui = NULL;
1198
#endif
1199
1200
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1201
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1202
// - DLL users: read comments above.
1203
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1204
0
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1205
0
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1206
#else
1207
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1208
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1209
#endif
1210
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1211
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1212
static void*                GImAllocatorUserData = NULL;
1213
1214
//-----------------------------------------------------------------------------
1215
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1216
//-----------------------------------------------------------------------------
1217
1218
ImGuiStyle::ImGuiStyle()
1219
0
{
1220
0
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1221
0
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1222
0
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1223
0
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1224
0
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1225
0
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1226
0
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1227
0
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1228
0
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1229
0
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1230
0
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1231
0
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1232
0
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1233
0
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1234
0
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1235
0
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1236
0
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1237
0
    CellPadding             = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1238
0
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1239
0
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1240
0
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1241
0
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1242
0
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1243
0
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1244
0
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1245
0
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1246
0
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1247
0
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1248
0
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1249
0
    TabBarBorderSize        = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1250
0
    TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1251
0
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1252
0
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1253
0
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1254
0
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1255
0
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1256
0
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1257
0
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1258
0
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1259
0
    DockingSeparatorSize    = 2.0f;             // Thickness of resizing border between docked windows
1260
0
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1261
0
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1262
0
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1263
0
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1264
0
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1265
0
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1266
1267
    // Behaviors
1268
0
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1269
0
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1270
0
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1271
0
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1272
0
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1273
1274
    // Default theme
1275
0
    ImGui::StyleColorsDark(this);
1276
0
}
1277
1278
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1279
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1280
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1281
0
{
1282
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1283
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1284
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1285
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1286
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1287
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1288
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1289
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1290
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1291
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1292
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1293
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1294
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1295
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1296
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1297
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1298
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1299
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1300
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1301
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1302
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1303
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1304
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1305
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1306
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1307
0
}
1308
1309
ImGuiIO::ImGuiIO()
1310
0
{
1311
    // Most fields are initialized with zero
1312
0
    memset(this, 0, sizeof(*this));
1313
0
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1314
1315
    // Settings
1316
0
    ConfigFlags = ImGuiConfigFlags_None;
1317
0
    BackendFlags = ImGuiBackendFlags_None;
1318
0
    DisplaySize = ImVec2(-1.0f, -1.0f);
1319
0
    DeltaTime = 1.0f / 60.0f;
1320
0
    IniSavingRate = 5.0f;
1321
0
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1322
0
    LogFilename = "imgui_log.txt";
1323
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1324
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1325
        KeyMap[i] = -1;
1326
#endif
1327
0
    UserData = NULL;
1328
1329
0
    Fonts = NULL;
1330
0
    FontGlobalScale = 1.0f;
1331
0
    FontDefault = NULL;
1332
0
    FontAllowUserScaling = false;
1333
0
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1334
1335
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1336
0
    ConfigDockingNoSplit = false;
1337
0
    ConfigDockingWithShift = false;
1338
0
    ConfigDockingAlwaysTabBar = false;
1339
0
    ConfigDockingTransparentPayload = false;
1340
1341
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1342
0
    ConfigViewportsNoAutoMerge = false;
1343
0
    ConfigViewportsNoTaskBarIcon = false;
1344
0
    ConfigViewportsNoDecoration = true;
1345
0
    ConfigViewportsNoDefaultParent = false;
1346
1347
    // Miscellaneous options
1348
0
    MouseDrawCursor = false;
1349
#ifdef __APPLE__
1350
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1351
#else
1352
0
    ConfigMacOSXBehaviors = false;
1353
0
#endif
1354
0
    ConfigInputTrickleEventQueue = true;
1355
0
    ConfigInputTextCursorBlink = true;
1356
0
    ConfigInputTextEnterKeepActive = false;
1357
0
    ConfigDragClickToInputText = false;
1358
0
    ConfigWindowsResizeFromEdges = true;
1359
0
    ConfigWindowsMoveFromTitleBarOnly = false;
1360
0
    ConfigMemoryCompactTimer = 60.0f;
1361
0
    ConfigDebugBeginReturnValueOnce = false;
1362
0
    ConfigDebugBeginReturnValueLoop = false;
1363
1364
    // Inputs Behaviors
1365
0
    MouseDoubleClickTime = 0.30f;
1366
0
    MouseDoubleClickMaxDist = 6.0f;
1367
0
    MouseDragThreshold = 6.0f;
1368
0
    KeyRepeatDelay = 0.275f;
1369
0
    KeyRepeatRate = 0.050f;
1370
1371
    // Platform Functions
1372
    // Note: Initialize() will setup default clipboard/ime handlers.
1373
0
    BackendPlatformName = BackendRendererName = NULL;
1374
0
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1375
0
    PlatformLocaleDecimalPoint = '.';
1376
1377
    // Input (NB: we already have memset zero the entire structure!)
1378
0
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1379
0
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1380
0
    MouseSource = ImGuiMouseSource_Mouse;
1381
0
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1382
0
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1383
0
    AppAcceptingEvents = true;
1384
0
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1385
0
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1386
0
}
1387
1388
// Pass in translated ASCII characters for text input.
1389
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1390
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1391
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1392
void ImGuiIO::AddInputCharacter(unsigned int c)
1393
0
{
1394
0
    IM_ASSERT(Ctx != NULL);
1395
0
    ImGuiContext& g = *Ctx;
1396
0
    if (c == 0 || !AppAcceptingEvents)
1397
0
        return;
1398
1399
0
    ImGuiInputEvent e;
1400
0
    e.Type = ImGuiInputEventType_Text;
1401
0
    e.Source = ImGuiInputSource_Keyboard;
1402
0
    e.EventId = g.InputEventsNextEventId++;
1403
0
    e.Text.Char = c;
1404
0
    g.InputEventsQueue.push_back(e);
1405
0
}
1406
1407
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1408
// we should save the high surrogate.
1409
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1410
0
{
1411
0
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1412
0
        return;
1413
1414
0
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1415
0
    {
1416
0
        if (InputQueueSurrogate != 0)
1417
0
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1418
0
        InputQueueSurrogate = c;
1419
0
        return;
1420
0
    }
1421
1422
0
    ImWchar cp = c;
1423
0
    if (InputQueueSurrogate != 0)
1424
0
    {
1425
0
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1426
0
        {
1427
0
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1428
0
        }
1429
0
        else
1430
0
        {
1431
0
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1432
0
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1433
#else
1434
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1435
#endif
1436
0
        }
1437
1438
0
        InputQueueSurrogate = 0;
1439
0
    }
1440
0
    AddInputCharacter((unsigned)cp);
1441
0
}
1442
1443
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1444
0
{
1445
0
    if (!AppAcceptingEvents)
1446
0
        return;
1447
0
    while (*utf8_chars != 0)
1448
0
    {
1449
0
        unsigned int c = 0;
1450
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1451
0
        AddInputCharacter(c);
1452
0
    }
1453
0
}
1454
1455
// Clear all incoming events.
1456
void ImGuiIO::ClearEventsQueue()
1457
0
{
1458
0
    IM_ASSERT(Ctx != NULL);
1459
0
    ImGuiContext& g = *Ctx;
1460
0
    g.InputEventsQueue.clear();
1461
0
}
1462
1463
// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1464
void ImGuiIO::ClearInputKeys()
1465
0
{
1466
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1467
    memset(KeysDown, 0, sizeof(KeysDown));
1468
#endif
1469
0
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1470
0
    {
1471
0
        KeysData[n].Down             = false;
1472
0
        KeysData[n].DownDuration     = -1.0f;
1473
0
        KeysData[n].DownDurationPrev = -1.0f;
1474
0
    }
1475
0
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1476
0
    KeyMods = ImGuiMod_None;
1477
0
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1478
0
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1479
0
    {
1480
0
        MouseDown[n] = false;
1481
0
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1482
0
    }
1483
0
    MouseWheel = MouseWheelH = 0.0f;
1484
0
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1485
0
}
1486
1487
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1488
// Current frame character buffer is now also cleared by ClearInputKeys().
1489
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1490
void ImGuiIO::ClearInputCharacters()
1491
{
1492
    InputQueueCharacters.resize(0);
1493
}
1494
#endif
1495
1496
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1497
0
{
1498
0
    ImGuiContext& g = *ctx;
1499
0
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1500
0
    {
1501
0
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1502
0
        if (e->Type != type)
1503
0
            continue;
1504
0
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1505
0
            continue;
1506
0
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1507
0
            continue;
1508
0
        return e;
1509
0
    }
1510
0
    return NULL;
1511
0
}
1512
1513
// Queue a new key down/up event.
1514
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1515
// - bool down:          Is the key down? use false to signify a key release.
1516
// - float analog_value: 0.0f..1.0f
1517
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1518
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1519
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1520
0
{
1521
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1522
0
    IM_ASSERT(Ctx != NULL);
1523
0
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1524
0
        return;
1525
0
    ImGuiContext& g = *Ctx;
1526
0
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1527
0
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1528
0
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1529
1530
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1531
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1532
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1533
    if (BackendUsingLegacyKeyArrays == -1)
1534
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1535
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1536
    BackendUsingLegacyKeyArrays = 0;
1537
#endif
1538
0
    if (ImGui::IsGamepadKey(key))
1539
0
        BackendUsingLegacyNavInputArray = false;
1540
1541
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1542
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1543
0
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1544
0
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1545
0
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1546
0
    if (latest_key_down == down && latest_key_analog == analog_value)
1547
0
        return;
1548
1549
    // Add event
1550
0
    ImGuiInputEvent e;
1551
0
    e.Type = ImGuiInputEventType_Key;
1552
0
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1553
0
    e.EventId = g.InputEventsNextEventId++;
1554
0
    e.Key.Key = key;
1555
0
    e.Key.Down = down;
1556
0
    e.Key.AnalogValue = analog_value;
1557
0
    g.InputEventsQueue.push_back(e);
1558
0
}
1559
1560
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1561
0
{
1562
0
    if (!AppAcceptingEvents)
1563
0
        return;
1564
0
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1565
0
}
1566
1567
// [Optional] Call after AddKeyEvent().
1568
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1569
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1570
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1571
0
{
1572
0
    if (key == ImGuiKey_None)
1573
0
        return;
1574
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1575
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1576
0
    IM_UNUSED(native_keycode);  // Yet unused
1577
0
    IM_UNUSED(native_scancode); // Yet unused
1578
1579
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1580
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1581
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1582
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1583
        return;
1584
    KeyMap[legacy_key] = key;
1585
    KeyMap[key] = legacy_key;
1586
#else
1587
0
    IM_UNUSED(key);
1588
0
    IM_UNUSED(native_legacy_index);
1589
0
#endif
1590
0
}
1591
1592
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1593
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1594
0
{
1595
0
    AppAcceptingEvents = accepting_events;
1596
0
}
1597
1598
// Queue a mouse move event
1599
void ImGuiIO::AddMousePosEvent(float x, float y)
1600
0
{
1601
0
    IM_ASSERT(Ctx != NULL);
1602
0
    ImGuiContext& g = *Ctx;
1603
0
    if (!AppAcceptingEvents)
1604
0
        return;
1605
1606
    // Apply same flooring as UpdateMouseInputs()
1607
0
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1608
1609
    // Filter duplicate
1610
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1611
0
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1612
0
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1613
0
        return;
1614
1615
0
    ImGuiInputEvent e;
1616
0
    e.Type = ImGuiInputEventType_MousePos;
1617
0
    e.Source = ImGuiInputSource_Mouse;
1618
0
    e.EventId = g.InputEventsNextEventId++;
1619
0
    e.MousePos.PosX = pos.x;
1620
0
    e.MousePos.PosY = pos.y;
1621
0
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1622
0
    g.InputEventsQueue.push_back(e);
1623
0
}
1624
1625
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1626
0
{
1627
0
    IM_ASSERT(Ctx != NULL);
1628
0
    ImGuiContext& g = *Ctx;
1629
0
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1630
0
    if (!AppAcceptingEvents)
1631
0
        return;
1632
1633
    // Filter duplicate
1634
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1635
0
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1636
0
    if (latest_button_down == down)
1637
0
        return;
1638
1639
0
    ImGuiInputEvent e;
1640
0
    e.Type = ImGuiInputEventType_MouseButton;
1641
0
    e.Source = ImGuiInputSource_Mouse;
1642
0
    e.EventId = g.InputEventsNextEventId++;
1643
0
    e.MouseButton.Button = mouse_button;
1644
0
    e.MouseButton.Down = down;
1645
0
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1646
0
    g.InputEventsQueue.push_back(e);
1647
0
}
1648
1649
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1650
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1651
0
{
1652
0
    IM_ASSERT(Ctx != NULL);
1653
0
    ImGuiContext& g = *Ctx;
1654
1655
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1656
0
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1657
0
        return;
1658
1659
0
    ImGuiInputEvent e;
1660
0
    e.Type = ImGuiInputEventType_MouseWheel;
1661
0
    e.Source = ImGuiInputSource_Mouse;
1662
0
    e.EventId = g.InputEventsNextEventId++;
1663
0
    e.MouseWheel.WheelX = wheel_x;
1664
0
    e.MouseWheel.WheelY = wheel_y;
1665
0
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1666
0
    g.InputEventsQueue.push_back(e);
1667
0
}
1668
1669
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1670
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1671
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1672
0
{
1673
0
    IM_ASSERT(Ctx != NULL);
1674
0
    ImGuiContext& g = *Ctx;
1675
0
    g.InputEventsNextMouseSource = source;
1676
0
}
1677
1678
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1679
0
{
1680
0
    IM_ASSERT(Ctx != NULL);
1681
0
    ImGuiContext& g = *Ctx;
1682
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1683
0
    if (!AppAcceptingEvents)
1684
0
        return;
1685
1686
    // Filter duplicate
1687
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1688
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1689
0
    if (latest_viewport_id == viewport_id)
1690
0
        return;
1691
1692
0
    ImGuiInputEvent e;
1693
0
    e.Type = ImGuiInputEventType_MouseViewport;
1694
0
    e.Source = ImGuiInputSource_Mouse;
1695
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1696
0
    g.InputEventsQueue.push_back(e);
1697
0
}
1698
1699
void ImGuiIO::AddFocusEvent(bool focused)
1700
0
{
1701
0
    IM_ASSERT(Ctx != NULL);
1702
0
    ImGuiContext& g = *Ctx;
1703
1704
    // Filter duplicate
1705
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1706
0
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1707
0
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1708
0
        return;
1709
1710
0
    ImGuiInputEvent e;
1711
0
    e.Type = ImGuiInputEventType_Focus;
1712
0
    e.EventId = g.InputEventsNextEventId++;
1713
0
    e.AppFocused.Focused = focused;
1714
0
    g.InputEventsQueue.push_back(e);
1715
0
}
1716
1717
//-----------------------------------------------------------------------------
1718
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1719
//-----------------------------------------------------------------------------
1720
1721
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1722
0
{
1723
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1724
0
    ImVec2 p_last = p1;
1725
0
    ImVec2 p_closest;
1726
0
    float p_closest_dist2 = FLT_MAX;
1727
0
    float t_step = 1.0f / (float)num_segments;
1728
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1729
0
    {
1730
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1731
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1732
0
        float dist2 = ImLengthSqr(p - p_line);
1733
0
        if (dist2 < p_closest_dist2)
1734
0
        {
1735
0
            p_closest = p_line;
1736
0
            p_closest_dist2 = dist2;
1737
0
        }
1738
0
        p_last = p_current;
1739
0
    }
1740
0
    return p_closest;
1741
0
}
1742
1743
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1744
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1745
0
{
1746
0
    float dx = x4 - x1;
1747
0
    float dy = y4 - y1;
1748
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1749
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1750
0
    d2 = (d2 >= 0) ? d2 : -d2;
1751
0
    d3 = (d3 >= 0) ? d3 : -d3;
1752
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1753
0
    {
1754
0
        ImVec2 p_current(x4, y4);
1755
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1756
0
        float dist2 = ImLengthSqr(p - p_line);
1757
0
        if (dist2 < p_closest_dist2)
1758
0
        {
1759
0
            p_closest = p_line;
1760
0
            p_closest_dist2 = dist2;
1761
0
        }
1762
0
        p_last = p_current;
1763
0
    }
1764
0
    else if (level < 10)
1765
0
    {
1766
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1767
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1768
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1769
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1770
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1771
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1772
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1773
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1774
0
    }
1775
0
}
1776
1777
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1778
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1779
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1780
0
{
1781
0
    IM_ASSERT(tess_tol > 0.0f);
1782
0
    ImVec2 p_last = p1;
1783
0
    ImVec2 p_closest;
1784
0
    float p_closest_dist2 = FLT_MAX;
1785
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1786
0
    return p_closest;
1787
0
}
1788
1789
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1790
0
{
1791
0
    ImVec2 ap = p - a;
1792
0
    ImVec2 ab_dir = b - a;
1793
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1794
0
    if (dot < 0.0f)
1795
0
        return a;
1796
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1797
0
    if (dot > ab_len_sqr)
1798
0
        return b;
1799
0
    return a + ab_dir * dot / ab_len_sqr;
1800
0
}
1801
1802
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1803
0
{
1804
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1805
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1806
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1807
0
    return ((b1 == b2) && (b2 == b3));
1808
0
}
1809
1810
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1811
0
{
1812
0
    ImVec2 v0 = b - a;
1813
0
    ImVec2 v1 = c - a;
1814
0
    ImVec2 v2 = p - a;
1815
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1816
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1817
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1818
0
    out_u = 1.0f - out_v - out_w;
1819
0
}
1820
1821
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1822
0
{
1823
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1824
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1825
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1826
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1827
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1828
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1829
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1830
0
    if (m == dist2_ab)
1831
0
        return proj_ab;
1832
0
    if (m == dist2_bc)
1833
0
        return proj_bc;
1834
0
    return proj_ca;
1835
0
}
1836
1837
//-----------------------------------------------------------------------------
1838
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1839
//-----------------------------------------------------------------------------
1840
1841
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1842
int ImStricmp(const char* str1, const char* str2)
1843
0
{
1844
0
    int d;
1845
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1846
0
    return d;
1847
0
}
1848
1849
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1850
0
{
1851
0
    int d = 0;
1852
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1853
0
    return d;
1854
0
}
1855
1856
void ImStrncpy(char* dst, const char* src, size_t count)
1857
0
{
1858
0
    if (count < 1)
1859
0
        return;
1860
0
    if (count > 1)
1861
0
        strncpy(dst, src, count - 1);
1862
0
    dst[count - 1] = 0;
1863
0
}
1864
1865
char* ImStrdup(const char* str)
1866
0
{
1867
0
    size_t len = strlen(str);
1868
0
    void* buf = IM_ALLOC(len + 1);
1869
0
    return (char*)memcpy(buf, (const void*)str, len + 1);
1870
0
}
1871
1872
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1873
0
{
1874
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1875
0
    size_t src_size = strlen(src) + 1;
1876
0
    if (dst_buf_size < src_size)
1877
0
    {
1878
0
        IM_FREE(dst);
1879
0
        dst = (char*)IM_ALLOC(src_size);
1880
0
        if (p_dst_size)
1881
0
            *p_dst_size = src_size;
1882
0
    }
1883
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1884
0
}
1885
1886
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1887
0
{
1888
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1889
0
    return p;
1890
0
}
1891
1892
int ImStrlenW(const ImWchar* str)
1893
0
{
1894
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1895
0
    int n = 0;
1896
0
    while (*str++) n++;
1897
0
    return n;
1898
0
}
1899
1900
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1901
const char* ImStreolRange(const char* str, const char* str_end)
1902
0
{
1903
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1904
0
    return p ? p : str_end;
1905
0
}
1906
1907
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1908
0
{
1909
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1910
0
        buf_mid_line--;
1911
0
    return buf_mid_line;
1912
0
}
1913
1914
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1915
0
{
1916
0
    if (!needle_end)
1917
0
        needle_end = needle + strlen(needle);
1918
1919
0
    const char un0 = (char)ImToUpper(*needle);
1920
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1921
0
    {
1922
0
        if (ImToUpper(*haystack) == un0)
1923
0
        {
1924
0
            const char* b = needle + 1;
1925
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1926
0
                if (ImToUpper(*a) != ImToUpper(*b))
1927
0
                    break;
1928
0
            if (b == needle_end)
1929
0
                return haystack;
1930
0
        }
1931
0
        haystack++;
1932
0
    }
1933
0
    return NULL;
1934
0
}
1935
1936
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1937
void ImStrTrimBlanks(char* buf)
1938
0
{
1939
0
    char* p = buf;
1940
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1941
0
        p++;
1942
0
    char* p_start = p;
1943
0
    while (*p != 0)                         // Find end of string
1944
0
        p++;
1945
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1946
0
        p--;
1947
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1948
0
        memmove(buf, p_start, p - p_start);
1949
0
    buf[p - p_start] = 0;                   // Zero terminate
1950
0
}
1951
1952
const char* ImStrSkipBlank(const char* str)
1953
0
{
1954
0
    while (str[0] == ' ' || str[0] == '\t')
1955
0
        str++;
1956
0
    return str;
1957
0
}
1958
1959
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1960
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1961
// B) When buf==NULL vsnprintf() will return the output size.
1962
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1963
1964
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1965
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1966
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1967
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1968
#ifdef IMGUI_USE_STB_SPRINTF
1969
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1970
#define STB_SPRINTF_IMPLEMENTATION
1971
#endif
1972
#ifdef IMGUI_STB_SPRINTF_FILENAME
1973
#include IMGUI_STB_SPRINTF_FILENAME
1974
#else
1975
#include "stb_sprintf.h"
1976
#endif
1977
#endif // #ifdef IMGUI_USE_STB_SPRINTF
1978
1979
#if defined(_MSC_VER) && !defined(vsnprintf)
1980
#define vsnprintf _vsnprintf
1981
#endif
1982
1983
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1984
0
{
1985
0
    va_list args;
1986
0
    va_start(args, fmt);
1987
#ifdef IMGUI_USE_STB_SPRINTF
1988
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1989
#else
1990
0
    int w = vsnprintf(buf, buf_size, fmt, args);
1991
0
#endif
1992
0
    va_end(args);
1993
0
    if (buf == NULL)
1994
0
        return w;
1995
0
    if (w == -1 || w >= (int)buf_size)
1996
0
        w = (int)buf_size - 1;
1997
0
    buf[w] = 0;
1998
0
    return w;
1999
0
}
2000
2001
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2002
0
{
2003
#ifdef IMGUI_USE_STB_SPRINTF
2004
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2005
#else
2006
0
    int w = vsnprintf(buf, buf_size, fmt, args);
2007
0
#endif
2008
0
    if (buf == NULL)
2009
0
        return w;
2010
0
    if (w == -1 || w >= (int)buf_size)
2011
0
        w = (int)buf_size - 1;
2012
0
    buf[w] = 0;
2013
0
    return w;
2014
0
}
2015
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2016
2017
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2018
0
{
2019
0
    va_list args;
2020
0
    va_start(args, fmt);
2021
0
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2022
0
    va_end(args);
2023
0
}
2024
2025
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2026
0
{
2027
0
    ImGuiContext& g = *GImGui;
2028
0
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2029
0
    {
2030
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2031
0
        if (buf == NULL)
2032
0
            buf = "(null)";
2033
0
        *out_buf = buf;
2034
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2035
0
    }
2036
0
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2037
0
    {
2038
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2039
0
        const char* buf = va_arg(args, const char*);
2040
0
        if (buf == NULL)
2041
0
        {
2042
0
            buf = "(null)";
2043
0
            buf_len = ImMin(buf_len, 6);
2044
0
        }
2045
0
        *out_buf = buf;
2046
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2047
0
    }
2048
0
    else
2049
0
    {
2050
0
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2051
0
        *out_buf = g.TempBuffer.Data;
2052
0
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2053
0
    }
2054
0
}
2055
2056
// CRC32 needs a 1KB lookup table (not cache friendly)
2057
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2058
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2059
static const ImU32 GCrc32LookupTable[256] =
2060
{
2061
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2062
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2063
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2064
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2065
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2066
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2067
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2068
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2069
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2070
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2071
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2072
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2073
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2074
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2075
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2076
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2077
};
2078
2079
// Known size hash
2080
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2081
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2082
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2083
0
{
2084
0
    ImU32 crc = ~seed;
2085
0
    const unsigned char* data = (const unsigned char*)data_p;
2086
0
    const ImU32* crc32_lut = GCrc32LookupTable;
2087
0
    while (data_size-- != 0)
2088
0
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2089
0
    return ~crc;
2090
0
}
2091
2092
// Zero-terminated string hash, with support for ### to reset back to seed value
2093
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2094
// Because this syntax is rarely used we are optimizing for the common case.
2095
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2096
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2097
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2098
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2099
0
{
2100
0
    seed = ~seed;
2101
0
    ImU32 crc = seed;
2102
0
    const unsigned char* data = (const unsigned char*)data_p;
2103
0
    const ImU32* crc32_lut = GCrc32LookupTable;
2104
0
    if (data_size != 0)
2105
0
    {
2106
0
        while (data_size-- != 0)
2107
0
        {
2108
0
            unsigned char c = *data++;
2109
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2110
0
                crc = seed;
2111
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2112
0
        }
2113
0
    }
2114
0
    else
2115
0
    {
2116
0
        while (unsigned char c = *data++)
2117
0
        {
2118
0
            if (c == '#' && data[0] == '#' && data[1] == '#')
2119
0
                crc = seed;
2120
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2121
0
        }
2122
0
    }
2123
0
    return ~crc;
2124
0
}
2125
2126
//-----------------------------------------------------------------------------
2127
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2128
//-----------------------------------------------------------------------------
2129
2130
// Default file functions
2131
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2132
2133
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2134
0
{
2135
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2136
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2137
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2138
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2139
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2140
2141
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2142
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2143
    wchar_t local_temp_stack[FILENAME_MAX];
2144
    ImVector<wchar_t> local_temp_heap;
2145
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2146
        local_temp_heap.resize(filename_wsize + mode_wsize);
2147
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2148
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2149
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2150
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2151
    return ::_wfopen(filename_wbuf, mode_wbuf);
2152
#else
2153
0
    return fopen(filename, mode);
2154
0
#endif
2155
0
}
2156
2157
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2158
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2159
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2160
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2161
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2162
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2163
2164
// Helper: Load file content into memory
2165
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2166
// This can't really be used with "rt" because fseek size won't match read size.
2167
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2168
0
{
2169
0
    IM_ASSERT(filename && mode);
2170
0
    if (out_file_size)
2171
0
        *out_file_size = 0;
2172
2173
0
    ImFileHandle f;
2174
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2175
0
        return NULL;
2176
2177
0
    size_t file_size = (size_t)ImFileGetSize(f);
2178
0
    if (file_size == (size_t)-1)
2179
0
    {
2180
0
        ImFileClose(f);
2181
0
        return NULL;
2182
0
    }
2183
2184
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2185
0
    if (file_data == NULL)
2186
0
    {
2187
0
        ImFileClose(f);
2188
0
        return NULL;
2189
0
    }
2190
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2191
0
    {
2192
0
        ImFileClose(f);
2193
0
        IM_FREE(file_data);
2194
0
        return NULL;
2195
0
    }
2196
0
    if (padding_bytes > 0)
2197
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2198
2199
0
    ImFileClose(f);
2200
0
    if (out_file_size)
2201
0
        *out_file_size = file_size;
2202
2203
0
    return file_data;
2204
0
}
2205
2206
//-----------------------------------------------------------------------------
2207
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2208
//-----------------------------------------------------------------------------
2209
2210
IM_MSVC_RUNTIME_CHECKS_OFF
2211
2212
// Convert UTF-8 to 32-bit character, process single character input.
2213
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2214
// We handle UTF-8 decoding error by skipping forward.
2215
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2216
0
{
2217
0
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2218
0
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2219
0
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2220
0
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2221
0
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2222
0
    int len = lengths[*(const unsigned char*)in_text >> 3];
2223
0
    int wanted = len + (len ? 0 : 1);
2224
2225
0
    if (in_text_end == NULL)
2226
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2227
2228
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2229
    // so it is fast even with excessive branching.
2230
0
    unsigned char s[4];
2231
0
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2232
0
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2233
0
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2234
0
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2235
2236
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2237
0
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2238
0
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2239
0
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2240
0
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2241
0
    *out_char >>= shiftc[len];
2242
2243
    // Accumulate the various error conditions.
2244
0
    int e = 0;
2245
0
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2246
0
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2247
0
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2248
0
    e |= (s[1] & 0xc0) >> 2;
2249
0
    e |= (s[2] & 0xc0) >> 4;
2250
0
    e |= (s[3]       ) >> 6;
2251
0
    e ^= 0x2a; // top two bits of each tail byte correct?
2252
0
    e >>= shifte[len];
2253
2254
0
    if (e)
2255
0
    {
2256
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2257
        // One byte is consumed in case of invalid first byte of in_text.
2258
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2259
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2260
0
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2261
0
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2262
0
    }
2263
2264
0
    return wanted;
2265
0
}
2266
2267
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2268
0
{
2269
0
    ImWchar* buf_out = buf;
2270
0
    ImWchar* buf_end = buf + buf_size;
2271
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2272
0
    {
2273
0
        unsigned int c;
2274
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2275
0
        *buf_out++ = (ImWchar)c;
2276
0
    }
2277
0
    *buf_out = 0;
2278
0
    if (in_text_remaining)
2279
0
        *in_text_remaining = in_text;
2280
0
    return (int)(buf_out - buf);
2281
0
}
2282
2283
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2284
0
{
2285
0
    int char_count = 0;
2286
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2287
0
    {
2288
0
        unsigned int c;
2289
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2290
0
        char_count++;
2291
0
    }
2292
0
    return char_count;
2293
0
}
2294
2295
// Based on stb_to_utf8() from github.com/nothings/stb/
2296
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2297
0
{
2298
0
    if (c < 0x80)
2299
0
    {
2300
0
        buf[0] = (char)c;
2301
0
        return 1;
2302
0
    }
2303
0
    if (c < 0x800)
2304
0
    {
2305
0
        if (buf_size < 2) return 0;
2306
0
        buf[0] = (char)(0xc0 + (c >> 6));
2307
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2308
0
        return 2;
2309
0
    }
2310
0
    if (c < 0x10000)
2311
0
    {
2312
0
        if (buf_size < 3) return 0;
2313
0
        buf[0] = (char)(0xe0 + (c >> 12));
2314
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2315
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2316
0
        return 3;
2317
0
    }
2318
0
    if (c <= 0x10FFFF)
2319
0
    {
2320
0
        if (buf_size < 4) return 0;
2321
0
        buf[0] = (char)(0xf0 + (c >> 18));
2322
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2323
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2324
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2325
0
        return 4;
2326
0
    }
2327
    // Invalid code point, the max unicode is 0x10FFFF
2328
0
    return 0;
2329
0
}
2330
2331
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2332
0
{
2333
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2334
0
    out_buf[count] = 0;
2335
0
    return out_buf;
2336
0
}
2337
2338
// Not optimal but we very rarely use this function.
2339
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2340
0
{
2341
0
    unsigned int unused = 0;
2342
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2343
0
}
2344
2345
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2346
0
{
2347
0
    if (c < 0x80) return 1;
2348
0
    if (c < 0x800) return 2;
2349
0
    if (c < 0x10000) return 3;
2350
0
    if (c <= 0x10FFFF) return 4;
2351
0
    return 3;
2352
0
}
2353
2354
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2355
0
{
2356
0
    char* buf_p = out_buf;
2357
0
    const char* buf_end = out_buf + out_buf_size;
2358
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2359
0
    {
2360
0
        unsigned int c = (unsigned int)(*in_text++);
2361
0
        if (c < 0x80)
2362
0
            *buf_p++ = (char)c;
2363
0
        else
2364
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2365
0
    }
2366
0
    *buf_p = 0;
2367
0
    return (int)(buf_p - out_buf);
2368
0
}
2369
2370
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2371
0
{
2372
0
    int bytes_count = 0;
2373
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2374
0
    {
2375
0
        unsigned int c = (unsigned int)(*in_text++);
2376
0
        if (c < 0x80)
2377
0
            bytes_count++;
2378
0
        else
2379
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2380
0
    }
2381
0
    return bytes_count;
2382
0
}
2383
2384
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2385
0
{
2386
0
    while (in_text_curr > in_text_start)
2387
0
    {
2388
0
        in_text_curr--;
2389
0
        if ((*in_text_curr & 0xC0) != 0x80)
2390
0
            return in_text_curr;
2391
0
    }
2392
0
    return in_text_start;
2393
0
}
2394
2395
IM_MSVC_RUNTIME_CHECKS_RESTORE
2396
2397
//-----------------------------------------------------------------------------
2398
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2399
// Note: The Convert functions are early design which are not consistent with other API.
2400
//-----------------------------------------------------------------------------
2401
2402
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2403
0
{
2404
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2405
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2406
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2407
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2408
0
    return IM_COL32(r, g, b, 0xFF);
2409
0
}
2410
2411
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2412
0
{
2413
0
    float s = 1.0f / 255.0f;
2414
0
    return ImVec4(
2415
0
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2416
0
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2417
0
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2418
0
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2419
0
}
2420
2421
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2422
0
{
2423
0
    ImU32 out;
2424
0
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2425
0
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2426
0
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2427
0
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2428
0
    return out;
2429
0
}
2430
2431
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2432
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2433
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2434
0
{
2435
0
    float K = 0.f;
2436
0
    if (g < b)
2437
0
    {
2438
0
        ImSwap(g, b);
2439
0
        K = -1.f;
2440
0
    }
2441
0
    if (r < g)
2442
0
    {
2443
0
        ImSwap(r, g);
2444
0
        K = -2.f / 6.f - K;
2445
0
    }
2446
2447
0
    const float chroma = r - (g < b ? g : b);
2448
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2449
0
    out_s = chroma / (r + 1e-20f);
2450
0
    out_v = r;
2451
0
}
2452
2453
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2454
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2455
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2456
0
{
2457
0
    if (s == 0.0f)
2458
0
    {
2459
        // gray
2460
0
        out_r = out_g = out_b = v;
2461
0
        return;
2462
0
    }
2463
2464
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2465
0
    int   i = (int)h;
2466
0
    float f = h - (float)i;
2467
0
    float p = v * (1.0f - s);
2468
0
    float q = v * (1.0f - s * f);
2469
0
    float t = v * (1.0f - s * (1.0f - f));
2470
2471
0
    switch (i)
2472
0
    {
2473
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2474
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2475
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2476
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2477
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2478
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2479
0
    }
2480
0
}
2481
2482
//-----------------------------------------------------------------------------
2483
// [SECTION] ImGuiStorage
2484
// Helper: Key->value storage
2485
//-----------------------------------------------------------------------------
2486
2487
// std::lower_bound but without the bullshit
2488
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2489
0
{
2490
0
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2491
0
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2492
0
    size_t count = (size_t)(last - first);
2493
0
    while (count > 0)
2494
0
    {
2495
0
        size_t count2 = count >> 1;
2496
0
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2497
0
        if (mid->key < key)
2498
0
        {
2499
0
            first = ++mid;
2500
0
            count -= count2 + 1;
2501
0
        }
2502
0
        else
2503
0
        {
2504
0
            count = count2;
2505
0
        }
2506
0
    }
2507
0
    return first;
2508
0
}
2509
2510
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2511
void ImGuiStorage::BuildSortByKey()
2512
0
{
2513
0
    struct StaticFunc
2514
0
    {
2515
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2516
0
        {
2517
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2518
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2519
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2520
0
            return 0;
2521
0
        }
2522
0
    };
2523
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2524
0
}
2525
2526
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2527
0
{
2528
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2529
0
    if (it == Data.end() || it->key != key)
2530
0
        return default_val;
2531
0
    return it->val_i;
2532
0
}
2533
2534
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2535
0
{
2536
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2537
0
}
2538
2539
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2540
0
{
2541
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2542
0
    if (it == Data.end() || it->key != key)
2543
0
        return default_val;
2544
0
    return it->val_f;
2545
0
}
2546
2547
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2548
0
{
2549
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2550
0
    if (it == Data.end() || it->key != key)
2551
0
        return NULL;
2552
0
    return it->val_p;
2553
0
}
2554
2555
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2556
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2557
0
{
2558
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2559
0
    if (it == Data.end() || it->key != key)
2560
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2561
0
    return &it->val_i;
2562
0
}
2563
2564
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2565
0
{
2566
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2567
0
}
2568
2569
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2570
0
{
2571
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2572
0
    if (it == Data.end() || it->key != key)
2573
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2574
0
    return &it->val_f;
2575
0
}
2576
2577
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2578
0
{
2579
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2580
0
    if (it == Data.end() || it->key != key)
2581
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2582
0
    return &it->val_p;
2583
0
}
2584
2585
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2586
void ImGuiStorage::SetInt(ImGuiID key, int val)
2587
0
{
2588
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2589
0
    if (it == Data.end() || it->key != key)
2590
0
        Data.insert(it, ImGuiStoragePair(key, val));
2591
0
    else
2592
0
        it->val_i = val;
2593
0
}
2594
2595
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2596
0
{
2597
0
    SetInt(key, val ? 1 : 0);
2598
0
}
2599
2600
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2601
0
{
2602
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2603
0
    if (it == Data.end() || it->key != key)
2604
0
        Data.insert(it, ImGuiStoragePair(key, val));
2605
0
    else
2606
0
        it->val_f = val;
2607
0
}
2608
2609
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2610
0
{
2611
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2612
0
    if (it == Data.end() || it->key != key)
2613
0
        Data.insert(it, ImGuiStoragePair(key, val));
2614
0
    else
2615
0
        it->val_p = val;
2616
0
}
2617
2618
void ImGuiStorage::SetAllInt(int v)
2619
0
{
2620
0
    for (int i = 0; i < Data.Size; i++)
2621
0
        Data[i].val_i = v;
2622
0
}
2623
2624
//-----------------------------------------------------------------------------
2625
// [SECTION] ImGuiTextFilter
2626
//-----------------------------------------------------------------------------
2627
2628
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2629
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2630
0
{
2631
0
    InputBuf[0] = 0;
2632
0
    CountGrep = 0;
2633
0
    if (default_filter)
2634
0
    {
2635
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2636
0
        Build();
2637
0
    }
2638
0
}
2639
2640
bool ImGuiTextFilter::Draw(const char* label, float width)
2641
0
{
2642
0
    if (width != 0.0f)
2643
0
        ImGui::SetNextItemWidth(width);
2644
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2645
0
    if (value_changed)
2646
0
        Build();
2647
0
    return value_changed;
2648
0
}
2649
2650
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2651
0
{
2652
0
    out->resize(0);
2653
0
    const char* wb = b;
2654
0
    const char* we = wb;
2655
0
    while (we < e)
2656
0
    {
2657
0
        if (*we == separator)
2658
0
        {
2659
0
            out->push_back(ImGuiTextRange(wb, we));
2660
0
            wb = we + 1;
2661
0
        }
2662
0
        we++;
2663
0
    }
2664
0
    if (wb != we)
2665
0
        out->push_back(ImGuiTextRange(wb, we));
2666
0
}
2667
2668
void ImGuiTextFilter::Build()
2669
0
{
2670
0
    Filters.resize(0);
2671
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2672
0
    input_range.split(',', &Filters);
2673
2674
0
    CountGrep = 0;
2675
0
    for (ImGuiTextRange& f : Filters)
2676
0
    {
2677
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2678
0
            f.b++;
2679
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2680
0
            f.e--;
2681
0
        if (f.empty())
2682
0
            continue;
2683
0
        if (f.b[0] != '-')
2684
0
            CountGrep += 1;
2685
0
    }
2686
0
}
2687
2688
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2689
0
{
2690
0
    if (Filters.empty())
2691
0
        return true;
2692
2693
0
    if (text == NULL)
2694
0
        text = "";
2695
2696
0
    for (const ImGuiTextRange& f : Filters)
2697
0
    {
2698
0
        if (f.empty())
2699
0
            continue;
2700
0
        if (f.b[0] == '-')
2701
0
        {
2702
            // Subtract
2703
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2704
0
                return false;
2705
0
        }
2706
0
        else
2707
0
        {
2708
            // Grep
2709
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2710
0
                return true;
2711
0
        }
2712
0
    }
2713
2714
    // Implicit * grep
2715
0
    if (CountGrep == 0)
2716
0
        return true;
2717
2718
0
    return false;
2719
0
}
2720
2721
//-----------------------------------------------------------------------------
2722
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2723
//-----------------------------------------------------------------------------
2724
2725
// On some platform vsnprintf() takes va_list by reference and modifies it.
2726
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2727
#ifndef va_copy
2728
#if defined(__GNUC__) || defined(__clang__)
2729
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2730
#else
2731
#define va_copy(dest, src) (dest = src)
2732
#endif
2733
#endif
2734
2735
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2736
2737
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2738
0
{
2739
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2740
2741
    // Add zero-terminator the first time
2742
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2743
0
    const int needed_sz = write_off + len;
2744
0
    if (write_off + len >= Buf.Capacity)
2745
0
    {
2746
0
        int new_capacity = Buf.Capacity * 2;
2747
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2748
0
    }
2749
2750
0
    Buf.resize(needed_sz);
2751
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2752
0
    Buf[write_off - 1 + len] = 0;
2753
0
}
2754
2755
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2756
0
{
2757
0
    va_list args;
2758
0
    va_start(args, fmt);
2759
0
    appendfv(fmt, args);
2760
0
    va_end(args);
2761
0
}
2762
2763
// Helper: Text buffer for logging/accumulating text
2764
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2765
0
{
2766
0
    va_list args_copy;
2767
0
    va_copy(args_copy, args);
2768
2769
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2770
0
    if (len <= 0)
2771
0
    {
2772
0
        va_end(args_copy);
2773
0
        return;
2774
0
    }
2775
2776
    // Add zero-terminator the first time
2777
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2778
0
    const int needed_sz = write_off + len;
2779
0
    if (write_off + len >= Buf.Capacity)
2780
0
    {
2781
0
        int new_capacity = Buf.Capacity * 2;
2782
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2783
0
    }
2784
2785
0
    Buf.resize(needed_sz);
2786
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2787
0
    va_end(args_copy);
2788
0
}
2789
2790
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2791
0
{
2792
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2793
0
    if (old_size == new_size)
2794
0
        return;
2795
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2796
0
        LineOffsets.push_back(EndOffset);
2797
0
    const char* base_end = base + new_size;
2798
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2799
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2800
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2801
0
    EndOffset = ImMax(EndOffset, new_size);
2802
0
}
2803
2804
//-----------------------------------------------------------------------------
2805
// [SECTION] ImGuiListClipper
2806
//-----------------------------------------------------------------------------
2807
2808
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2809
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2810
static bool GetSkipItemForListClipping()
2811
0
{
2812
0
    ImGuiContext& g = *GImGui;
2813
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2814
0
}
2815
2816
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2817
0
{
2818
0
    if (ranges.Size - offset <= 1)
2819
0
        return;
2820
2821
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2822
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2823
0
        for (int i = offset; i < sort_end + offset; ++i)
2824
0
            if (ranges[i].Min > ranges[i + 1].Min)
2825
0
                ImSwap(ranges[i], ranges[i + 1]);
2826
2827
    // Now fuse ranges together as much as possible.
2828
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2829
0
    {
2830
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2831
0
        if (ranges[i - 1].Max < ranges[i].Min)
2832
0
            continue;
2833
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2834
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2835
0
        ranges.erase(ranges.Data + i);
2836
0
        i--;
2837
0
    }
2838
0
}
2839
2840
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2841
0
{
2842
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2843
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2844
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2845
0
    ImGuiContext& g = *GImGui;
2846
0
    ImGuiWindow* window = g.CurrentWindow;
2847
0
    float off_y = pos_y - window->DC.CursorPos.y;
2848
0
    window->DC.CursorPos.y = pos_y;
2849
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2850
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2851
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2852
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2853
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2854
0
    if (ImGuiTable* table = g.CurrentTable)
2855
0
    {
2856
0
        if (table->IsInsideRow)
2857
0
            ImGui::TableEndRow(table);
2858
0
        table->RowPosY2 = window->DC.CursorPos.y;
2859
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2860
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2861
0
        table->RowBgColorCounter += row_increase;
2862
0
    }
2863
0
}
2864
2865
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2866
0
{
2867
    // StartPosY starts from ItemsFrozen hence the subtraction
2868
    // Perform the add and multiply with double to allow seeking through larger ranges
2869
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2870
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2871
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2872
0
}
2873
2874
ImGuiListClipper::ImGuiListClipper()
2875
0
{
2876
0
    memset(this, 0, sizeof(*this));
2877
0
}
2878
2879
ImGuiListClipper::~ImGuiListClipper()
2880
0
{
2881
0
    End();
2882
0
}
2883
2884
void ImGuiListClipper::Begin(int items_count, float items_height)
2885
0
{
2886
0
    if (Ctx == NULL)
2887
0
        Ctx = ImGui::GetCurrentContext();
2888
2889
0
    ImGuiContext& g = *Ctx;
2890
0
    ImGuiWindow* window = g.CurrentWindow;
2891
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2892
2893
0
    if (ImGuiTable* table = g.CurrentTable)
2894
0
        if (table->IsInsideRow)
2895
0
            ImGui::TableEndRow(table);
2896
2897
0
    StartPosY = window->DC.CursorPos.y;
2898
0
    ItemsHeight = items_height;
2899
0
    ItemsCount = items_count;
2900
0
    DisplayStart = -1;
2901
0
    DisplayEnd = 0;
2902
2903
    // Acquire temporary buffer
2904
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2905
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2906
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2907
0
    data->Reset(this);
2908
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2909
0
    TempData = data;
2910
0
}
2911
2912
void ImGuiListClipper::End()
2913
0
{
2914
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2915
0
    {
2916
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2917
0
        ImGuiContext& g = *Ctx;
2918
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2919
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2920
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2921
2922
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2923
0
        IM_ASSERT(data->ListClipper == this);
2924
0
        data->StepNo = data->Ranges.Size;
2925
0
        if (--g.ClipperTempDataStacked > 0)
2926
0
        {
2927
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2928
0
            data->ListClipper->TempData = data;
2929
0
        }
2930
0
        TempData = NULL;
2931
0
    }
2932
0
    ItemsCount = -1;
2933
0
}
2934
2935
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2936
0
{
2937
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2938
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2939
0
    IM_ASSERT(item_begin <= item_end);
2940
0
    if (item_begin < item_end)
2941
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2942
0
}
2943
2944
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2945
0
{
2946
0
    ImGuiContext& g = *clipper->Ctx;
2947
0
    ImGuiWindow* window = g.CurrentWindow;
2948
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2949
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2950
2951
0
    ImGuiTable* table = g.CurrentTable;
2952
0
    if (table && table->IsInsideRow)
2953
0
        ImGui::TableEndRow(table);
2954
2955
    // No items
2956
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2957
0
        return false;
2958
2959
    // While we are in frozen row state, keep displaying items one by one, unclipped
2960
    // FIXME: Could be stored as a table-agnostic state.
2961
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2962
0
    {
2963
0
        clipper->DisplayStart = data->ItemsFrozen;
2964
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2965
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2966
0
            data->ItemsFrozen++;
2967
0
        return true;
2968
0
    }
2969
2970
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2971
0
    bool calc_clipping = false;
2972
0
    if (data->StepNo == 0)
2973
0
    {
2974
0
        clipper->StartPosY = window->DC.CursorPos.y;
2975
0
        if (clipper->ItemsHeight <= 0.0f)
2976
0
        {
2977
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2978
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2979
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2980
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2981
0
            data->StepNo = 1;
2982
0
            return true;
2983
0
        }
2984
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2985
0
    }
2986
2987
    // Step 1: Let the clipper infer height from first range
2988
0
    if (clipper->ItemsHeight <= 0.0f)
2989
0
    {
2990
0
        IM_ASSERT(data->StepNo == 1);
2991
0
        if (table)
2992
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2993
2994
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2995
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2996
0
        if (affected_by_floating_point_precision)
2997
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2998
2999
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3000
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3001
0
    }
3002
3003
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3004
0
    const int already_submitted = clipper->DisplayEnd;
3005
0
    if (calc_clipping)
3006
0
    {
3007
0
        if (g.LogEnabled)
3008
0
        {
3009
            // If logging is active, do not perform any clipping
3010
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3011
0
        }
3012
0
        else
3013
0
        {
3014
            // Add range selected to be included for navigation
3015
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3016
0
            if (is_nav_request)
3017
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3018
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3019
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3020
3021
            // Add focused/active item
3022
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3023
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3024
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3025
3026
            // Add visible range
3027
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3028
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3029
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3030
0
        }
3031
3032
        // Convert position ranges to item index ranges
3033
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3034
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3035
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3036
0
        for (ImGuiListClipperRange& range : data->Ranges)
3037
0
            if (range.PosToIndexConvert)
3038
0
            {
3039
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3040
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3041
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3042
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3043
0
                range.PosToIndexConvert = false;
3044
0
            }
3045
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3046
0
    }
3047
3048
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3049
0
    while (data->StepNo < data->Ranges.Size)
3050
0
    {
3051
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3052
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3053
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3054
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3055
0
        data->StepNo++;
3056
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3057
0
            continue;
3058
0
        return true;
3059
0
    }
3060
3061
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3062
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3063
0
    if (clipper->ItemsCount < INT_MAX)
3064
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3065
3066
0
    return false;
3067
0
}
3068
3069
bool ImGuiListClipper::Step()
3070
0
{
3071
0
    ImGuiContext& g = *Ctx;
3072
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3073
0
    bool ret = ImGuiListClipper_StepInternal(this);
3074
0
    if (ret && (DisplayStart == DisplayEnd))
3075
0
        ret = false;
3076
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3077
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3078
0
    if (need_items_height && ItemsHeight > 0.0f)
3079
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3080
0
    if (ret)
3081
0
    {
3082
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3083
0
    }
3084
0
    else
3085
0
    {
3086
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3087
0
        End();
3088
0
    }
3089
0
    return ret;
3090
0
}
3091
3092
//-----------------------------------------------------------------------------
3093
// [SECTION] STYLING
3094
//-----------------------------------------------------------------------------
3095
3096
ImGuiStyle& ImGui::GetStyle()
3097
0
{
3098
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3099
0
    return GImGui->Style;
3100
0
}
3101
3102
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3103
0
{
3104
0
    ImGuiStyle& style = GImGui->Style;
3105
0
    ImVec4 c = style.Colors[idx];
3106
0
    c.w *= style.Alpha * alpha_mul;
3107
0
    return ColorConvertFloat4ToU32(c);
3108
0
}
3109
3110
ImU32 ImGui::GetColorU32(const ImVec4& col)
3111
0
{
3112
0
    ImGuiStyle& style = GImGui->Style;
3113
0
    ImVec4 c = col;
3114
0
    c.w *= style.Alpha;
3115
0
    return ColorConvertFloat4ToU32(c);
3116
0
}
3117
3118
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3119
0
{
3120
0
    ImGuiStyle& style = GImGui->Style;
3121
0
    return style.Colors[idx];
3122
0
}
3123
3124
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3125
0
{
3126
0
    ImGuiStyle& style = GImGui->Style;
3127
0
    alpha_mul *= style.Alpha;
3128
0
    if (alpha_mul >= 1.0f)
3129
0
        return col;
3130
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3131
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3132
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3133
0
}
3134
3135
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3136
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3137
0
{
3138
0
    ImGuiContext& g = *GImGui;
3139
0
    ImGuiColorMod backup;
3140
0
    backup.Col = idx;
3141
0
    backup.BackupValue = g.Style.Colors[idx];
3142
0
    g.ColorStack.push_back(backup);
3143
0
    if (g.DebugFlashStyleColorIdx != idx)
3144
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3145
0
}
3146
3147
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3148
0
{
3149
0
    ImGuiContext& g = *GImGui;
3150
0
    ImGuiColorMod backup;
3151
0
    backup.Col = idx;
3152
0
    backup.BackupValue = g.Style.Colors[idx];
3153
0
    g.ColorStack.push_back(backup);
3154
0
    if (g.DebugFlashStyleColorIdx != idx)
3155
0
        g.Style.Colors[idx] = col;
3156
0
}
3157
3158
void ImGui::PopStyleColor(int count)
3159
0
{
3160
0
    ImGuiContext& g = *GImGui;
3161
0
    if (g.ColorStack.Size < count)
3162
0
    {
3163
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3164
0
        count = g.ColorStack.Size;
3165
0
    }
3166
0
    while (count > 0)
3167
0
    {
3168
0
        ImGuiColorMod& backup = g.ColorStack.back();
3169
0
        g.Style.Colors[backup.Col] = backup.BackupValue;
3170
0
        g.ColorStack.pop_back();
3171
0
        count--;
3172
0
    }
3173
0
}
3174
3175
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3176
{
3177
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3178
};
3179
3180
static const ImGuiDataVarInfo GStyleVarInfo[] =
3181
{
3182
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                 // ImGuiStyleVar_Alpha
3183
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },         // ImGuiStyleVar_DisabledAlpha
3184
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },         // ImGuiStyleVar_WindowPadding
3185
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },        // ImGuiStyleVar_WindowRounding
3186
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },      // ImGuiStyleVar_WindowBorderSize
3187
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },         // ImGuiStyleVar_WindowMinSize
3188
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },      // ImGuiStyleVar_WindowTitleAlign
3189
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },         // ImGuiStyleVar_ChildRounding
3190
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },       // ImGuiStyleVar_ChildBorderSize
3191
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },         // ImGuiStyleVar_PopupRounding
3192
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },       // ImGuiStyleVar_PopupBorderSize
3193
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },          // ImGuiStyleVar_FramePadding
3194
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },         // ImGuiStyleVar_FrameRounding
3195
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },       // ImGuiStyleVar_FrameBorderSize
3196
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },           // ImGuiStyleVar_ItemSpacing
3197
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },      // ImGuiStyleVar_ItemInnerSpacing
3198
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },         // ImGuiStyleVar_IndentSpacing
3199
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },           // ImGuiStyleVar_CellPadding
3200
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },         // ImGuiStyleVar_ScrollbarSize
3201
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },     // ImGuiStyleVar_ScrollbarRounding
3202
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },           // ImGuiStyleVar_GrabMinSize
3203
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },          // ImGuiStyleVar_GrabRounding
3204
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },           // ImGuiStyleVar_TabRounding
3205
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },         // ImGuiStyleVar_TabBorderSize
3206
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },      // ImGuiStyleVar_TabBarBorderSize
3207
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},// ImGuiStyleVar_TableAngledHeadersAngle
3208
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },       // ImGuiStyleVar_ButtonTextAlign
3209
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },   // ImGuiStyleVar_SelectableTextAlign
3210
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3211
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },    // ImGuiStyleVar_SeparatorTextAlign
3212
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },  // ImGuiStyleVar_SeparatorTextPadding
3213
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },  // ImGuiStyleVar_DockingSeparatorSize
3214
};
3215
3216
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3217
0
{
3218
0
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3219
0
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3220
0
    return &GStyleVarInfo[idx];
3221
0
}
3222
3223
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3224
0
{
3225
0
    ImGuiContext& g = *GImGui;
3226
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3227
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3228
0
    {
3229
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3230
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3231
0
        *pvar = val;
3232
0
        return;
3233
0
    }
3234
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3235
0
}
3236
3237
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3238
0
{
3239
0
    ImGuiContext& g = *GImGui;
3240
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3241
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3242
0
    {
3243
0
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3244
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3245
0
        *pvar = val;
3246
0
        return;
3247
0
    }
3248
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3249
0
}
3250
3251
void ImGui::PopStyleVar(int count)
3252
0
{
3253
0
    ImGuiContext& g = *GImGui;
3254
0
    if (g.StyleVarStack.Size < count)
3255
0
    {
3256
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3257
0
        count = g.StyleVarStack.Size;
3258
0
    }
3259
0
    while (count > 0)
3260
0
    {
3261
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3262
0
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3263
0
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3264
0
        void* data = info->GetVarPtr(&g.Style);
3265
0
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3266
0
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3267
0
        g.StyleVarStack.pop_back();
3268
0
        count--;
3269
0
    }
3270
0
}
3271
3272
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3273
0
{
3274
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3275
0
    switch (idx)
3276
0
    {
3277
0
    case ImGuiCol_Text: return "Text";
3278
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3279
0
    case ImGuiCol_WindowBg: return "WindowBg";
3280
0
    case ImGuiCol_ChildBg: return "ChildBg";
3281
0
    case ImGuiCol_PopupBg: return "PopupBg";
3282
0
    case ImGuiCol_Border: return "Border";
3283
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3284
0
    case ImGuiCol_FrameBg: return "FrameBg";
3285
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3286
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3287
0
    case ImGuiCol_TitleBg: return "TitleBg";
3288
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3289
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3290
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3291
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3292
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3293
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3294
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3295
0
    case ImGuiCol_CheckMark: return "CheckMark";
3296
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3297
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3298
0
    case ImGuiCol_Button: return "Button";
3299
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3300
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3301
0
    case ImGuiCol_Header: return "Header";
3302
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3303
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3304
0
    case ImGuiCol_Separator: return "Separator";
3305
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3306
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3307
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3308
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3309
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3310
0
    case ImGuiCol_Tab: return "Tab";
3311
0
    case ImGuiCol_TabHovered: return "TabHovered";
3312
0
    case ImGuiCol_TabActive: return "TabActive";
3313
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3314
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3315
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3316
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3317
0
    case ImGuiCol_PlotLines: return "PlotLines";
3318
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3319
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3320
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3321
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3322
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3323
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3324
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3325
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3326
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3327
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3328
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3329
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3330
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3331
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3332
0
    }
3333
0
    IM_ASSERT(0);
3334
0
    return "Unknown";
3335
0
}
3336
3337
3338
//-----------------------------------------------------------------------------
3339
// [SECTION] RENDER HELPERS
3340
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3341
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3342
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3343
//-----------------------------------------------------------------------------
3344
3345
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3346
0
{
3347
0
    const char* text_display_end = text;
3348
0
    if (!text_end)
3349
0
        text_end = (const char*)-1;
3350
3351
0
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3352
0
        text_display_end++;
3353
0
    return text_display_end;
3354
0
}
3355
3356
// Internal ImGui functions to render text
3357
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3358
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3359
0
{
3360
0
    ImGuiContext& g = *GImGui;
3361
0
    ImGuiWindow* window = g.CurrentWindow;
3362
3363
    // Hide anything after a '##' string
3364
0
    const char* text_display_end;
3365
0
    if (hide_text_after_hash)
3366
0
    {
3367
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3368
0
    }
3369
0
    else
3370
0
    {
3371
0
        if (!text_end)
3372
0
            text_end = text + strlen(text); // FIXME-OPT
3373
0
        text_display_end = text_end;
3374
0
    }
3375
3376
0
    if (text != text_display_end)
3377
0
    {
3378
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3379
0
        if (g.LogEnabled)
3380
0
            LogRenderedText(&pos, text, text_display_end);
3381
0
    }
3382
0
}
3383
3384
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3385
0
{
3386
0
    ImGuiContext& g = *GImGui;
3387
0
    ImGuiWindow* window = g.CurrentWindow;
3388
3389
0
    if (!text_end)
3390
0
        text_end = text + strlen(text); // FIXME-OPT
3391
3392
0
    if (text != text_end)
3393
0
    {
3394
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3395
0
        if (g.LogEnabled)
3396
0
            LogRenderedText(&pos, text, text_end);
3397
0
    }
3398
0
}
3399
3400
// Default clip_rect uses (pos_min,pos_max)
3401
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3402
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3403
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3404
// better advantage of the render function taking size into account for coarse clipping.
3405
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3406
0
{
3407
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3408
0
    ImVec2 pos = pos_min;
3409
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3410
3411
0
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3412
0
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3413
0
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3414
0
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3415
0
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3416
3417
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3418
0
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3419
0
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3420
3421
    // Render
3422
0
    if (need_clipping)
3423
0
    {
3424
0
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3425
0
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3426
0
    }
3427
0
    else
3428
0
    {
3429
0
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3430
0
    }
3431
0
}
3432
3433
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3434
0
{
3435
    // Hide anything after a '##' string
3436
0
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3437
0
    const int text_len = (int)(text_display_end - text);
3438
0
    if (text_len == 0)
3439
0
        return;
3440
3441
0
    ImGuiContext& g = *GImGui;
3442
0
    ImGuiWindow* window = g.CurrentWindow;
3443
0
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3444
0
    if (g.LogEnabled)
3445
0
        LogRenderedText(&pos_min, text, text_display_end);
3446
0
}
3447
3448
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3449
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3450
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3451
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3452
0
{
3453
0
    ImGuiContext& g = *GImGui;
3454
0
    if (text_end_full == NULL)
3455
0
        text_end_full = FindRenderedTextEnd(text);
3456
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3457
3458
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3459
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3460
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3461
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3462
0
    if (text_size.x > pos_max.x - pos_min.x)
3463
0
    {
3464
        // Hello wo...
3465
        // |       |   |
3466
        // min   max   ellipsis_max
3467
        //          <-> this is generally some padding value
3468
3469
0
        const ImFont* font = draw_list->_Data->Font;
3470
0
        const float font_size = draw_list->_Data->FontSize;
3471
0
        const float font_scale = font_size / font->FontSize;
3472
0
        const char* text_end_ellipsis = NULL;
3473
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3474
3475
        // We can now claim the space between pos_max.x and ellipsis_max.x
3476
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3477
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3478
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3479
0
        {
3480
            // Always display at least 1 character if there's no room for character + ellipsis
3481
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3482
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3483
0
        }
3484
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3485
0
        {
3486
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3487
0
            text_end_ellipsis--;
3488
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3489
0
        }
3490
3491
        // Render text, render ellipsis
3492
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3493
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3494
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3495
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3496
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3497
0
    }
3498
0
    else
3499
0
    {
3500
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3501
0
    }
3502
3503
0
    if (g.LogEnabled)
3504
0
        LogRenderedText(&pos_min, text, text_end_full);
3505
0
}
3506
3507
// Render a rectangle shaped with optional rounding and borders
3508
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3509
0
{
3510
0
    ImGuiContext& g = *GImGui;
3511
0
    ImGuiWindow* window = g.CurrentWindow;
3512
0
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3513
0
    const float border_size = g.Style.FrameBorderSize;
3514
0
    if (border && border_size > 0.0f)
3515
0
    {
3516
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3517
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3518
0
    }
3519
0
}
3520
3521
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3522
0
{
3523
0
    ImGuiContext& g = *GImGui;
3524
0
    ImGuiWindow* window = g.CurrentWindow;
3525
0
    const float border_size = g.Style.FrameBorderSize;
3526
0
    if (border_size > 0.0f)
3527
0
    {
3528
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3529
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3530
0
    }
3531
0
}
3532
3533
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3534
0
{
3535
0
    ImGuiContext& g = *GImGui;
3536
0
    if (id != g.NavId)
3537
0
        return;
3538
0
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3539
0
        return;
3540
0
    ImGuiWindow* window = g.CurrentWindow;
3541
0
    if (window->DC.NavHideHighlightOneFrame)
3542
0
        return;
3543
3544
0
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3545
0
    ImRect display_rect = bb;
3546
0
    display_rect.ClipWith(window->ClipRect);
3547
0
    const float thickness = 2.0f;
3548
0
    if (flags & ImGuiNavHighlightFlags_Compact)
3549
0
    {
3550
0
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3551
0
    }
3552
0
    else
3553
0
    {
3554
0
        const float distance = 3.0f + thickness * 0.5f;
3555
0
        display_rect.Expand(ImVec2(distance, distance));
3556
0
        bool fully_visible = window->ClipRect.Contains(display_rect);
3557
0
        if (!fully_visible)
3558
0
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3559
0
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3560
0
        if (!fully_visible)
3561
0
            window->DrawList->PopClipRect();
3562
0
    }
3563
0
}
3564
3565
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3566
0
{
3567
0
    ImGuiContext& g = *GImGui;
3568
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3569
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3570
0
    for (ImGuiViewportP* viewport : g.Viewports)
3571
0
    {
3572
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3573
0
        ImVec2 offset, size, uv[4];
3574
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3575
0
            continue;
3576
0
        const ImVec2 pos = base_pos - offset;
3577
0
        const float scale = base_scale * viewport->DpiScale;
3578
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3579
0
            continue;
3580
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3581
0
        ImTextureID tex_id = font_atlas->TexID;
3582
0
        draw_list->PushTextureID(tex_id);
3583
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3584
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3585
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3586
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3587
0
        draw_list->PopTextureID();
3588
0
    }
3589
0
}
3590
3591
//-----------------------------------------------------------------------------
3592
// [SECTION] INITIALIZATION, SHUTDOWN
3593
//-----------------------------------------------------------------------------
3594
3595
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3596
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3597
ImGuiContext* ImGui::GetCurrentContext()
3598
0
{
3599
0
    return GImGui;
3600
0
}
3601
3602
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3603
0
{
3604
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3605
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3606
#else
3607
0
    GImGui = ctx;
3608
0
#endif
3609
0
}
3610
3611
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3612
0
{
3613
0
    GImAllocatorAllocFunc = alloc_func;
3614
0
    GImAllocatorFreeFunc = free_func;
3615
0
    GImAllocatorUserData = user_data;
3616
0
}
3617
3618
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3619
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3620
0
{
3621
0
    *p_alloc_func = GImAllocatorAllocFunc;
3622
0
    *p_free_func = GImAllocatorFreeFunc;
3623
0
    *p_user_data = GImAllocatorUserData;
3624
0
}
3625
3626
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3627
0
{
3628
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3629
0
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3630
0
    SetCurrentContext(ctx);
3631
0
    Initialize();
3632
0
    if (prev_ctx != NULL)
3633
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3634
0
    return ctx;
3635
0
}
3636
3637
void ImGui::DestroyContext(ImGuiContext* ctx)
3638
0
{
3639
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3640
0
    if (ctx == NULL) //-V1051
3641
0
        ctx = prev_ctx;
3642
0
    SetCurrentContext(ctx);
3643
0
    Shutdown();
3644
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3645
0
    IM_DELETE(ctx);
3646
0
}
3647
3648
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3649
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3650
{
3651
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3652
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3653
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3654
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3655
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3656
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3657
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3658
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3659
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3660
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3661
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3662
};
3663
3664
void ImGui::Initialize()
3665
0
{
3666
0
    ImGuiContext& g = *GImGui;
3667
0
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3668
3669
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3670
0
    {
3671
0
        ImGuiSettingsHandler ini_handler;
3672
0
        ini_handler.TypeName = "Window";
3673
0
        ini_handler.TypeHash = ImHashStr("Window");
3674
0
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3675
0
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3676
0
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3677
0
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3678
0
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3679
0
        AddSettingsHandler(&ini_handler);
3680
0
    }
3681
0
    TableSettingsAddSettingsHandler();
3682
3683
    // Setup default localization table
3684
0
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3685
3686
    // Setup default platform clipboard/IME handlers.
3687
0
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3688
0
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3689
0
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3690
0
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3691
3692
    // Create default viewport
3693
0
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3694
0
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3695
0
    viewport->Idx = 0;
3696
0
    viewport->PlatformWindowCreated = true;
3697
0
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3698
0
    g.Viewports.push_back(viewport);
3699
0
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3700
0
    g.ViewportCreatedCount++;
3701
0
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3702
3703
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3704
0
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3705
0
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3706
0
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3707
0
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3708
0
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3709
0
            g.KeysMayBeCharInput.SetBit(key);
3710
3711
0
#ifdef IMGUI_HAS_DOCK
3712
    // Initialize Docking
3713
0
    DockContextInitialize(&g);
3714
0
#endif
3715
3716
0
    g.Initialized = true;
3717
0
}
3718
3719
// This function is merely here to free heap allocations.
3720
void ImGui::Shutdown()
3721
0
{
3722
0
    ImGuiContext& g = *GImGui;
3723
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3724
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3725
3726
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3727
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3728
0
    {
3729
0
        g.IO.Fonts->Locked = false;
3730
0
        IM_DELETE(g.IO.Fonts);
3731
0
    }
3732
0
    g.IO.Fonts = NULL;
3733
0
    g.DrawListSharedData.TempBuffer.clear();
3734
3735
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3736
0
    if (!g.Initialized)
3737
0
        return;
3738
3739
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3740
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3741
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3742
3743
    // Destroy platform windows
3744
0
    DestroyPlatformWindows();
3745
3746
    // Shutdown extensions
3747
0
    DockContextShutdown(&g);
3748
3749
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3750
3751
    // Clear everything else
3752
0
    g.Windows.clear_delete();
3753
0
    g.WindowsFocusOrder.clear();
3754
0
    g.WindowsTempSortBuffer.clear();
3755
0
    g.CurrentWindow = NULL;
3756
0
    g.CurrentWindowStack.clear();
3757
0
    g.WindowsById.Clear();
3758
0
    g.NavWindow = NULL;
3759
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3760
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3761
0
    g.MovingWindow = NULL;
3762
3763
0
    g.KeysRoutingTable.Clear();
3764
3765
0
    g.ColorStack.clear();
3766
0
    g.StyleVarStack.clear();
3767
0
    g.FontStack.clear();
3768
0
    g.OpenPopupStack.clear();
3769
0
    g.BeginPopupStack.clear();
3770
0
    g.NavTreeNodeStack.clear();
3771
3772
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3773
0
    g.Viewports.clear_delete();
3774
3775
0
    g.TabBars.Clear();
3776
0
    g.CurrentTabBarStack.clear();
3777
0
    g.ShrinkWidthBuffer.clear();
3778
3779
0
    g.ClipperTempData.clear_destruct();
3780
3781
0
    g.Tables.Clear();
3782
0
    g.TablesTempData.clear_destruct();
3783
0
    g.DrawChannelsTempMergeBuffer.clear();
3784
3785
0
    g.ClipboardHandlerData.clear();
3786
0
    g.MenusIdSubmittedThisFrame.clear();
3787
0
    g.InputTextState.ClearFreeMemory();
3788
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3789
3790
0
    g.SettingsWindows.clear();
3791
0
    g.SettingsHandlers.clear();
3792
3793
0
    if (g.LogFile)
3794
0
    {
3795
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3796
0
        if (g.LogFile != stdout)
3797
0
#endif
3798
0
            ImFileClose(g.LogFile);
3799
0
        g.LogFile = NULL;
3800
0
    }
3801
0
    g.LogBuffer.clear();
3802
0
    g.DebugLogBuf.clear();
3803
0
    g.DebugLogIndex.clear();
3804
3805
0
    g.Initialized = false;
3806
0
}
3807
3808
// No specific ordering/dependency support, will see as needed
3809
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3810
0
{
3811
0
    ImGuiContext& g = *ctx;
3812
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3813
0
    g.Hooks.push_back(*hook);
3814
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3815
0
    return g.HookIdNext;
3816
0
}
3817
3818
// Deferred removal, avoiding issue with changing vector while iterating it
3819
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3820
0
{
3821
0
    ImGuiContext& g = *ctx;
3822
0
    IM_ASSERT(hook_id != 0);
3823
0
    for (ImGuiContextHook& hook : g.Hooks)
3824
0
        if (hook.HookId == hook_id)
3825
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3826
0
}
3827
3828
// Call context hooks (used by e.g. test engine)
3829
// We assume a small number of hooks so all stored in same array
3830
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3831
0
{
3832
0
    ImGuiContext& g = *ctx;
3833
0
    for (ImGuiContextHook& hook : g.Hooks)
3834
0
        if (hook.Type == hook_type)
3835
0
            hook.Callback(&g, &hook);
3836
0
}
3837
3838
3839
//-----------------------------------------------------------------------------
3840
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3841
//-----------------------------------------------------------------------------
3842
3843
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3844
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3845
0
{
3846
0
    memset(this, 0, sizeof(*this));
3847
0
    Ctx = ctx;
3848
0
    Name = ImStrdup(name);
3849
0
    NameBufLen = (int)strlen(name) + 1;
3850
0
    ID = ImHashStr(name);
3851
0
    IDStack.push_back(ID);
3852
0
    ViewportAllowPlatformMonitorExtend = -1;
3853
0
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3854
0
    MoveId = GetID("#MOVE");
3855
0
    TabId = GetID("#TAB");
3856
0
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3857
0
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3858
0
    AutoFitFramesX = AutoFitFramesY = -1;
3859
0
    AutoPosLastDirection = ImGuiDir_None;
3860
0
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3861
0
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3862
0
    LastFrameActive = -1;
3863
0
    LastFrameJustFocused = -1;
3864
0
    LastTimeActive = -1.0f;
3865
0
    FontWindowScale = FontDpiScale = 1.0f;
3866
0
    SettingsOffset = -1;
3867
0
    DockOrder = -1;
3868
0
    DrawList = &DrawListInst;
3869
0
    DrawList->_Data = &Ctx->DrawListSharedData;
3870
0
    DrawList->_OwnerName = Name;
3871
0
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3872
0
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3873
0
}
3874
3875
ImGuiWindow::~ImGuiWindow()
3876
0
{
3877
0
    IM_ASSERT(DrawList == &DrawListInst);
3878
0
    IM_DELETE(Name);
3879
0
    ColumnsStorage.clear_destruct();
3880
0
}
3881
3882
static void SetCurrentWindow(ImGuiWindow* window)
3883
0
{
3884
0
    ImGuiContext& g = *GImGui;
3885
0
    g.CurrentWindow = window;
3886
0
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3887
0
    if (window)
3888
0
    {
3889
0
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3890
0
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3891
0
    }
3892
0
}
3893
3894
void ImGui::GcCompactTransientMiscBuffers()
3895
0
{
3896
0
    ImGuiContext& g = *GImGui;
3897
0
    g.ItemFlagsStack.clear();
3898
0
    g.GroupStack.clear();
3899
0
    TableGcCompactSettings();
3900
0
}
3901
3902
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3903
// Not freed:
3904
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3905
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3906
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3907
0
{
3908
0
    window->MemoryCompacted = true;
3909
0
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3910
0
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3911
0
    window->IDStack.clear();
3912
0
    window->DrawList->_ClearFreeMemory();
3913
0
    window->DC.ChildWindows.clear();
3914
0
    window->DC.ItemWidthStack.clear();
3915
0
    window->DC.TextWrapPosStack.clear();
3916
0
}
3917
3918
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3919
0
{
3920
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3921
    // The other buffers tends to amortize much faster.
3922
0
    window->MemoryCompacted = false;
3923
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3924
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3925
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3926
0
}
3927
3928
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3929
0
{
3930
0
    ImGuiContext& g = *GImGui;
3931
3932
    // Clear previous active id
3933
0
    if (g.ActiveId != 0)
3934
0
    {
3935
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3936
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3937
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3938
0
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3939
0
        {
3940
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3941
0
            g.MovingWindow = NULL;
3942
0
        }
3943
3944
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3945
        // but since this is currently quite an exception we'll leave it as is.
3946
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3947
0
        if (g.InputTextState.ID == g.ActiveId)
3948
0
            InputTextDeactivateHook(g.ActiveId);
3949
0
    }
3950
3951
    // Set active id
3952
0
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3953
0
    if (g.ActiveIdIsJustActivated)
3954
0
    {
3955
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3956
0
        g.ActiveIdTimer = 0.0f;
3957
0
        g.ActiveIdHasBeenPressedBefore = false;
3958
0
        g.ActiveIdHasBeenEditedBefore = false;
3959
0
        g.ActiveIdMouseButton = -1;
3960
0
        if (id != 0)
3961
0
        {
3962
0
            g.LastActiveId = id;
3963
0
            g.LastActiveIdTimer = 0.0f;
3964
0
        }
3965
0
    }
3966
0
    g.ActiveId = id;
3967
0
    g.ActiveIdAllowOverlap = false;
3968
0
    g.ActiveIdNoClearOnFocusLoss = false;
3969
0
    g.ActiveIdWindow = window;
3970
0
    g.ActiveIdHasBeenEditedThisFrame = false;
3971
0
    g.ActiveIdFromShortcut = false;
3972
0
    if (id)
3973
0
    {
3974
0
        g.ActiveIdIsAlive = id;
3975
0
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3976
0
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3977
0
    }
3978
3979
    // Clear declaration of inputs claimed by the widget
3980
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3981
0
    g.ActiveIdUsingNavDirMask = 0x00;
3982
0
    g.ActiveIdUsingAllKeyboardKeys = false;
3983
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3984
    g.ActiveIdUsingNavInputMask = 0x00;
3985
#endif
3986
0
}
3987
3988
void ImGui::ClearActiveID()
3989
0
{
3990
0
    SetActiveID(0, NULL); // g.ActiveId = 0;
3991
0
}
3992
3993
void ImGui::SetHoveredID(ImGuiID id)
3994
0
{
3995
0
    ImGuiContext& g = *GImGui;
3996
0
    g.HoveredId = id;
3997
0
    g.HoveredIdAllowOverlap = false;
3998
0
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3999
0
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4000
0
}
4001
4002
ImGuiID ImGui::GetHoveredID()
4003
0
{
4004
0
    ImGuiContext& g = *GImGui;
4005
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4006
0
}
4007
4008
void ImGui::MarkItemEdited(ImGuiID id)
4009
0
{
4010
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4011
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4012
0
    ImGuiContext& g = *GImGui;
4013
0
    if (g.LockMarkEdited > 0)
4014
0
        return;
4015
0
    if (g.ActiveId == id || g.ActiveId == 0)
4016
0
    {
4017
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4018
0
        g.ActiveIdHasBeenEditedBefore = true;
4019
0
    }
4020
4021
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4022
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4023
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4024
4025
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4026
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4027
0
}
4028
4029
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4030
0
{
4031
    // An active popup disable hovering on other windows (apart from its own children)
4032
    // FIXME-OPT: This could be cached/stored within the window.
4033
0
    ImGuiContext& g = *GImGui;
4034
0
    if (g.NavWindow)
4035
0
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4036
0
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4037
0
            {
4038
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4039
                // NB: The 'else' is important because Modal windows are also Popups.
4040
0
                bool want_inhibit = false;
4041
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4042
0
                    want_inhibit = true;
4043
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4044
0
                    want_inhibit = true;
4045
4046
                // Inhibit hover unless the window is within the stack of our modal/popup
4047
0
                if (want_inhibit)
4048
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4049
0
                        return false;
4050
0
            }
4051
4052
    // Filter by viewport
4053
0
    if (window->Viewport != g.MouseViewport)
4054
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4055
0
            return false;
4056
4057
0
    return true;
4058
0
}
4059
4060
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4061
0
{
4062
0
    ImGuiContext& g = *GImGui;
4063
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4064
0
        return g.Style.HoverDelayNormal;
4065
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4066
0
        return g.Style.HoverDelayShort;
4067
0
    return 0.0f;
4068
0
}
4069
4070
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4071
0
{
4072
    // Allow instance flags to override shared flags
4073
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4074
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4075
0
    return user_flags | shared_flags;
4076
0
}
4077
4078
// This is roughly matching the behavior of internal-facing ItemHoverable()
4079
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4080
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4081
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4082
0
{
4083
0
    ImGuiContext& g = *GImGui;
4084
0
    ImGuiWindow* window = g.CurrentWindow;
4085
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4086
4087
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4088
0
    {
4089
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4090
0
            return false;
4091
0
        if (!IsItemFocused())
4092
0
            return false;
4093
4094
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4095
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4096
0
    }
4097
0
    else
4098
0
    {
4099
        // Test for bounding box overlap, as updated as ItemAdd()
4100
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4101
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4102
0
            return false;
4103
4104
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4105
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4106
4107
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4108
4109
        // Done with rectangle culling so we can perform heavier checks now
4110
        // Test if we are hovering the right window (our window could be behind another window)
4111
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4112
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4113
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4114
        // the test that has been running for a long while.
4115
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4116
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4117
0
                return false;
4118
4119
        // Test if another item is active (e.g. being dragged)
4120
0
        const ImGuiID id = g.LastItemData.ID;
4121
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4122
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4123
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4124
0
                    return false;
4125
4126
        // Test if interactions on this window are blocked by an active popup or modal.
4127
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4128
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4129
0
            return false;
4130
4131
        // Test if the item is disabled
4132
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4133
0
            return false;
4134
4135
        // Special handling for calling after Begin() which represent the title bar or tab.
4136
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4137
        // will never be overwritten so we need to detect the case.
4138
0
        if (id == window->MoveId && window->WriteAccessed)
4139
0
            return false;
4140
4141
        // Test if using AllowOverlap and overlapped
4142
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4143
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4144
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4145
0
                    return false;
4146
0
    }
4147
4148
    // Handle hover delay
4149
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4150
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4151
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4152
0
    {
4153
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4154
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4155
0
            g.HoverItemDelayTimer = 0.0f;
4156
0
        g.HoverItemDelayId = hover_delay_id;
4157
4158
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4159
        // but once unlocked on a given item we also moving.
4160
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4161
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4162
0
            return false;
4163
4164
0
        if (g.HoverItemDelayTimer < delay)
4165
0
            return false;
4166
0
    }
4167
4168
0
    return true;
4169
0
}
4170
4171
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4172
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4173
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4174
// If you used this in your legacy/custom widgets code:
4175
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4176
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4177
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4178
0
{
4179
0
    ImGuiContext& g = *GImGui;
4180
0
    ImGuiWindow* window = g.CurrentWindow;
4181
0
    if (g.HoveredWindow != window)
4182
0
        return false;
4183
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4184
0
        return false;
4185
4186
0
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4187
0
        return false;
4188
0
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4189
0
        if (!g.ActiveIdFromShortcut)
4190
0
            return false;
4191
4192
    // Done with rectangle culling so we can perform heavier checks now.
4193
0
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4194
0
    {
4195
0
        g.HoveredIdDisabled = true;
4196
0
        return false;
4197
0
    }
4198
4199
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4200
    // hover test in widgets code. We could also decide to split this function is two.
4201
0
    if (id != 0)
4202
0
    {
4203
        // Drag source doesn't report as hovered
4204
0
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4205
0
            return false;
4206
4207
0
        SetHoveredID(id);
4208
4209
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4210
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4211
0
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4212
0
        {
4213
0
            g.HoveredIdAllowOverlap = true;
4214
0
            if (g.HoveredIdPreviousFrame != id)
4215
0
                return false;
4216
0
        }
4217
0
    }
4218
4219
    // When disabled we'll return false but still set HoveredId
4220
0
    if (item_flags & ImGuiItemFlags_Disabled)
4221
0
    {
4222
        // Release active id if turning disabled
4223
0
        if (g.ActiveId == id && id != 0)
4224
0
            ClearActiveID();
4225
0
        g.HoveredIdDisabled = true;
4226
0
        return false;
4227
0
    }
4228
4229
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4230
0
    if (id != 0)
4231
0
    {
4232
        // [DEBUG] Item Picker tool!
4233
        // We perform the check here because reaching is path is rare (1~ time a frame),
4234
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4235
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4236
0
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4237
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4238
0
        if (g.DebugItemPickerBreakId == id)
4239
0
            IM_DEBUG_BREAK();
4240
0
    }
4241
0
#endif
4242
4243
0
    if (g.NavDisableMouseHover)
4244
0
        return false;
4245
4246
0
    return true;
4247
0
}
4248
4249
// FIXME: This is inlined/duplicated in ItemAdd()
4250
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4251
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4252
0
{
4253
0
    ImGuiContext& g = *GImGui;
4254
0
    ImGuiWindow* window = g.CurrentWindow;
4255
0
    if (!bb.Overlaps(window->ClipRect))
4256
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4257
0
            if (!g.LogEnabled)
4258
0
                return true;
4259
0
    return false;
4260
0
}
4261
4262
// This is also inlined in ItemAdd()
4263
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4264
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4265
0
{
4266
0
    ImGuiContext& g = *GImGui;
4267
0
    g.LastItemData.ID = item_id;
4268
0
    g.LastItemData.InFlags = in_flags;
4269
0
    g.LastItemData.StatusFlags = item_flags;
4270
0
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4271
0
}
4272
4273
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4274
0
{
4275
0
    if (wrap_pos_x < 0.0f)
4276
0
        return 0.0f;
4277
4278
0
    ImGuiContext& g = *GImGui;
4279
0
    ImGuiWindow* window = g.CurrentWindow;
4280
0
    if (wrap_pos_x == 0.0f)
4281
0
    {
4282
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4283
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4284
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4285
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4286
        //else
4287
0
        wrap_pos_x = window->WorkRect.Max.x;
4288
0
    }
4289
0
    else if (wrap_pos_x > 0.0f)
4290
0
    {
4291
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4292
0
    }
4293
4294
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4295
0
}
4296
4297
// IM_ALLOC() == ImGui::MemAlloc()
4298
void* ImGui::MemAlloc(size_t size)
4299
0
{
4300
0
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4301
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4302
0
    if (ImGuiContext* ctx = GImGui)
4303
0
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4304
0
#endif
4305
0
    return ptr;
4306
0
}
4307
4308
// IM_FREE() == ImGui::MemFree()
4309
void ImGui::MemFree(void* ptr)
4310
0
{
4311
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4312
0
    if (ptr != NULL)
4313
0
        if (ImGuiContext* ctx = GImGui)
4314
0
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4315
0
#endif
4316
0
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4317
0
}
4318
4319
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4320
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4321
0
{
4322
0
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4323
0
    IM_UNUSED(ptr);
4324
0
    if (entry->FrameCount != frame_count)
4325
0
    {
4326
0
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4327
0
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4328
0
        entry->FrameCount = frame_count;
4329
0
        entry->AllocCount = entry->FreeCount = 0;
4330
0
    }
4331
0
    if (size != (size_t)-1)
4332
0
    {
4333
0
        entry->AllocCount++;
4334
0
        info->TotalAllocCount++;
4335
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4336
0
    }
4337
0
    else
4338
0
    {
4339
0
        entry->FreeCount++;
4340
0
        info->TotalFreeCount++;
4341
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4342
0
    }
4343
0
}
4344
4345
const char* ImGui::GetClipboardText()
4346
0
{
4347
0
    ImGuiContext& g = *GImGui;
4348
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4349
0
}
4350
4351
void ImGui::SetClipboardText(const char* text)
4352
0
{
4353
0
    ImGuiContext& g = *GImGui;
4354
0
    if (g.IO.SetClipboardTextFn)
4355
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4356
0
}
4357
4358
const char* ImGui::GetVersion()
4359
0
{
4360
0
    return IMGUI_VERSION;
4361
0
}
4362
4363
ImGuiIO& ImGui::GetIO()
4364
0
{
4365
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4366
0
    return GImGui->IO;
4367
0
}
4368
4369
ImGuiPlatformIO& ImGui::GetPlatformIO()
4370
0
{
4371
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4372
0
    return GImGui->PlatformIO;
4373
0
}
4374
4375
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4376
ImDrawData* ImGui::GetDrawData()
4377
0
{
4378
0
    ImGuiContext& g = *GImGui;
4379
0
    ImGuiViewportP* viewport = g.Viewports[0];
4380
0
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4381
0
}
4382
4383
double ImGui::GetTime()
4384
0
{
4385
0
    return GImGui->Time;
4386
0
}
4387
4388
int ImGui::GetFrameCount()
4389
0
{
4390
0
    return GImGui->FrameCount;
4391
0
}
4392
4393
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4394
0
{
4395
    // Create the draw list on demand, because they are not frequently used for all viewports
4396
0
    ImGuiContext& g = *GImGui;
4397
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4398
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4399
0
    if (draw_list == NULL)
4400
0
    {
4401
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4402
0
        draw_list->_OwnerName = drawlist_name;
4403
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4404
0
    }
4405
4406
    // Our ImDrawList system requires that there is always a command
4407
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4408
0
    {
4409
0
        draw_list->_ResetForNewFrame();
4410
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4411
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4412
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4413
0
    }
4414
0
    return draw_list;
4415
0
}
4416
4417
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4418
0
{
4419
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4420
0
}
4421
4422
ImDrawList* ImGui::GetBackgroundDrawList()
4423
0
{
4424
0
    ImGuiContext& g = *GImGui;
4425
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4426
0
}
4427
4428
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4429
0
{
4430
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4431
0
}
4432
4433
ImDrawList* ImGui::GetForegroundDrawList()
4434
0
{
4435
0
    ImGuiContext& g = *GImGui;
4436
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4437
0
}
4438
4439
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4440
0
{
4441
0
    return &GImGui->DrawListSharedData;
4442
0
}
4443
4444
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4445
0
{
4446
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4447
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4448
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4449
0
    ImGuiContext& g = *GImGui;
4450
0
    FocusWindow(window);
4451
0
    SetActiveID(window->MoveId, window);
4452
0
    g.NavDisableHighlight = true;
4453
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4454
0
    g.ActiveIdNoClearOnFocusLoss = true;
4455
0
    SetActiveIdUsingAllKeyboardKeys();
4456
4457
0
    bool can_move_window = true;
4458
0
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4459
0
        can_move_window = false;
4460
0
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4461
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4462
0
            can_move_window = false;
4463
0
    if (can_move_window)
4464
0
        g.MovingWindow = window;
4465
0
}
4466
4467
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4468
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4469
0
{
4470
0
    ImGuiContext& g = *GImGui;
4471
0
    bool can_undock_node = false;
4472
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4473
0
    {
4474
        // Can undock if:
4475
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4476
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4477
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4478
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4479
0
            can_undock_node = true;
4480
0
    }
4481
4482
0
    const bool clicked = IsMouseClicked(0);
4483
0
    const bool dragging = IsMouseDragging(0);
4484
0
    if (can_undock_node && dragging)
4485
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4486
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4487
0
        StartMouseMovingWindow(window);
4488
0
}
4489
4490
// Handle mouse moving window
4491
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4492
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4493
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4494
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4495
void ImGui::UpdateMouseMovingWindowNewFrame()
4496
0
{
4497
0
    ImGuiContext& g = *GImGui;
4498
0
    if (g.MovingWindow != NULL)
4499
0
    {
4500
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4501
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4502
0
        KeepAliveID(g.ActiveId);
4503
0
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4504
0
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4505
4506
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4507
0
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4508
0
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4509
0
        {
4510
0
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4511
0
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4512
0
            {
4513
0
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4514
0
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4515
0
                {
4516
0
                    moving_window->Viewport->Pos = pos;
4517
0
                    moving_window->Viewport->UpdateWorkRect();
4518
0
                }
4519
0
            }
4520
0
            FocusWindow(g.MovingWindow);
4521
0
        }
4522
0
        else
4523
0
        {
4524
0
            if (!window_disappared)
4525
0
            {
4526
                // Try to merge the window back into the main viewport.
4527
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4528
0
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4529
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4530
4531
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4532
0
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4533
0
                    g.MouseViewport = moving_window->Viewport;
4534
4535
                // Clear the NoInput window flag set by the Viewport system
4536
0
                if (moving_window->Viewport)
4537
0
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4538
0
            }
4539
4540
0
            g.MovingWindow = NULL;
4541
0
            ClearActiveID();
4542
0
        }
4543
0
    }
4544
0
    else
4545
0
    {
4546
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4547
0
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4548
0
        {
4549
0
            KeepAliveID(g.ActiveId);
4550
0
            if (!g.IO.MouseDown[0])
4551
0
                ClearActiveID();
4552
0
        }
4553
0
    }
4554
0
}
4555
4556
// Initiate moving window when clicking on empty space or title bar.
4557
// Handle left-click and right-click focus.
4558
void ImGui::UpdateMouseMovingWindowEndFrame()
4559
0
{
4560
0
    ImGuiContext& g = *GImGui;
4561
0
    if (g.ActiveId != 0 || g.HoveredId != 0)
4562
0
        return;
4563
4564
    // Unless we just made a window/popup appear
4565
0
    if (g.NavWindow && g.NavWindow->Appearing)
4566
0
        return;
4567
4568
    // Click on empty space to focus window and start moving
4569
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4570
0
    if (g.IO.MouseClicked[0])
4571
0
    {
4572
        // Handle the edge case of a popup being closed while clicking in its empty space.
4573
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4574
0
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4575
0
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4576
4577
0
        if (root_window != NULL && !is_closed_popup)
4578
0
        {
4579
0
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4580
4581
            // Cancel moving if clicked outside of title bar
4582
0
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4583
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4584
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4585
0
                        g.MovingWindow = NULL;
4586
4587
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4588
0
            if (g.HoveredIdDisabled)
4589
0
                g.MovingWindow = NULL;
4590
0
        }
4591
0
        else if (root_window == NULL && g.NavWindow != NULL)
4592
0
        {
4593
            // Clicking on void disable focus
4594
0
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4595
0
        }
4596
0
    }
4597
4598
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4599
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4600
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4601
0
    if (g.IO.MouseClicked[1])
4602
0
    {
4603
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4604
        // This is where we can trim the popup stack.
4605
0
        ImGuiWindow* modal = GetTopMostPopupModal();
4606
0
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4607
0
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4608
0
    }
4609
0
}
4610
4611
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4612
// Need to keep in sync with SetWindowPos()
4613
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4614
0
{
4615
0
    window->Pos += delta;
4616
0
    window->ClipRect.Translate(delta);
4617
0
    window->OuterRectClipped.Translate(delta);
4618
0
    window->InnerRect.Translate(delta);
4619
0
    window->DC.CursorPos += delta;
4620
0
    window->DC.CursorStartPos += delta;
4621
0
    window->DC.CursorMaxPos += delta;
4622
0
    window->DC.IdealMaxPos += delta;
4623
0
}
4624
4625
static void ScaleWindow(ImGuiWindow* window, float scale)
4626
0
{
4627
0
    ImVec2 origin = window->Viewport->Pos;
4628
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4629
0
    window->Size = ImTrunc(window->Size * scale);
4630
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4631
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4632
0
}
4633
4634
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4635
0
{
4636
0
    return (window->Active) && (!window->Hidden);
4637
0
}
4638
4639
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4640
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4641
0
{
4642
0
    ImGuiContext& g = *GImGui;
4643
0
    ImGuiIO& io = g.IO;
4644
0
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4645
4646
    // Find the window hovered by mouse:
4647
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4648
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4649
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4650
0
    bool clear_hovered_windows = false;
4651
0
    FindHoveredWindow();
4652
0
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4653
4654
    // Modal windows prevents mouse from hovering behind them.
4655
0
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4656
0
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4657
0
        clear_hovered_windows = true;
4658
4659
    // Disabled mouse?
4660
0
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4661
0
        clear_hovered_windows = true;
4662
4663
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4664
    // won't report hovering nor request capture even while dragging over our windows afterward.
4665
0
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4666
0
    const bool has_open_modal = (modal_window != NULL);
4667
0
    int mouse_earliest_down = -1;
4668
0
    bool mouse_any_down = false;
4669
0
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4670
0
    {
4671
0
        if (io.MouseClicked[i])
4672
0
        {
4673
0
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4674
0
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4675
0
        }
4676
0
        mouse_any_down |= io.MouseDown[i];
4677
0
        if (io.MouseDown[i])
4678
0
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4679
0
                mouse_earliest_down = i;
4680
0
    }
4681
0
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4682
0
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4683
4684
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4685
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4686
0
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4687
0
    if (!mouse_avail && !mouse_dragging_extern_payload)
4688
0
        clear_hovered_windows = true;
4689
4690
0
    if (clear_hovered_windows)
4691
0
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4692
4693
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4694
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4695
0
    if (g.WantCaptureMouseNextFrame != -1)
4696
0
    {
4697
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4698
0
    }
4699
0
    else
4700
0
    {
4701
0
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4702
0
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4703
0
    }
4704
4705
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4706
0
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4707
0
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4708
0
        io.WantCaptureKeyboard = true;
4709
0
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4710
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4711
4712
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4713
0
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4714
0
}
4715
4716
// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4717
static void SetupDrawListSharedData()
4718
0
{
4719
0
    ImGuiContext& g = *GImGui;
4720
0
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4721
0
    for (ImGuiViewportP* viewport : g.Viewports)
4722
0
        virtual_space.Add(viewport->GetMainRect());
4723
0
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4724
0
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4725
0
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4726
0
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4727
0
    if (g.Style.AntiAliasedLines)
4728
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4729
0
    if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4730
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4731
0
    if (g.Style.AntiAliasedFill)
4732
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4733
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4734
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4735
0
}
4736
4737
void ImGui::NewFrame()
4738
0
{
4739
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4740
0
    ImGuiContext& g = *GImGui;
4741
4742
    // Remove pending delete hooks before frame start.
4743
    // This deferred removal avoid issues of removal while iterating the hook vector
4744
0
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4745
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4746
0
            g.Hooks.erase(&g.Hooks[n]);
4747
4748
0
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4749
4750
    // Check and assert for various common IO and Configuration mistakes
4751
0
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4752
0
    ErrorCheckNewFrameSanityChecks();
4753
0
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4754
4755
    // Load settings on first frame, save settings when modified (after a delay)
4756
0
    UpdateSettings();
4757
4758
0
    g.Time += g.IO.DeltaTime;
4759
0
    g.WithinFrameScope = true;
4760
0
    g.FrameCount += 1;
4761
0
    g.TooltipOverrideCount = 0;
4762
0
    g.WindowsActiveCount = 0;
4763
0
    g.MenusIdSubmittedThisFrame.resize(0);
4764
4765
    // Calculate frame-rate for the user, as a purely luxurious feature
4766
0
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4767
0
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4768
0
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4769
0
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4770
0
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4771
4772
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4773
0
    g.InputEventsTrail.resize(0);
4774
0
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4775
4776
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4777
0
    UpdateViewportsNewFrame();
4778
4779
    // Setup current font and draw list shared data
4780
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4781
0
    g.IO.Fonts->Locked = true;
4782
0
    SetupDrawListSharedData();
4783
0
    SetCurrentFont(GetDefaultFont());
4784
0
    IM_ASSERT(g.Font->IsLoaded());
4785
4786
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4787
0
    for (ImGuiViewportP* viewport : g.Viewports)
4788
0
    {
4789
0
        viewport->DrawData = NULL;
4790
0
        viewport->DrawDataP.Valid = false;
4791
0
    }
4792
4793
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4794
0
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4795
0
        KeepAliveID(g.DragDropPayload.SourceId);
4796
4797
    // Update HoveredId data
4798
0
    if (!g.HoveredIdPreviousFrame)
4799
0
        g.HoveredIdTimer = 0.0f;
4800
0
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4801
0
        g.HoveredIdNotActiveTimer = 0.0f;
4802
0
    if (g.HoveredId)
4803
0
        g.HoveredIdTimer += g.IO.DeltaTime;
4804
0
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4805
0
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4806
0
    g.HoveredIdPreviousFrame = g.HoveredId;
4807
0
    g.HoveredId = 0;
4808
0
    g.HoveredIdAllowOverlap = false;
4809
0
    g.HoveredIdDisabled = false;
4810
4811
    // Clear ActiveID if the item is not alive anymore.
4812
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4813
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4814
0
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4815
0
    {
4816
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4817
0
        ClearActiveID();
4818
0
    }
4819
4820
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4821
0
    if (g.ActiveId)
4822
0
        g.ActiveIdTimer += g.IO.DeltaTime;
4823
0
    g.LastActiveIdTimer += g.IO.DeltaTime;
4824
0
    g.ActiveIdPreviousFrame = g.ActiveId;
4825
0
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4826
0
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4827
0
    g.ActiveIdIsAlive = 0;
4828
0
    g.ActiveIdHasBeenEditedThisFrame = false;
4829
0
    g.ActiveIdPreviousFrameIsAlive = false;
4830
0
    g.ActiveIdIsJustActivated = false;
4831
0
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4832
0
        g.TempInputId = 0;
4833
0
    if (g.ActiveId == 0)
4834
0
    {
4835
0
        g.ActiveIdUsingNavDirMask = 0x00;
4836
0
        g.ActiveIdUsingAllKeyboardKeys = false;
4837
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4838
        g.ActiveIdUsingNavInputMask = 0x00;
4839
#endif
4840
0
    }
4841
4842
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4843
    if (g.ActiveId == 0)
4844
        g.ActiveIdUsingNavInputMask = 0;
4845
    else if (g.ActiveIdUsingNavInputMask != 0)
4846
    {
4847
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4848
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4849
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4850
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4851
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4852
            IM_ASSERT(0); // Other values unsupported
4853
    }
4854
#endif
4855
4856
    // Record when we have been stationary as this state is preserved while over same item.
4857
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4858
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4859
0
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4860
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4861
0
    else if (g.HoverItemDelayId == 0)
4862
0
        g.HoverItemUnlockedStationaryId = 0;
4863
0
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4864
0
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4865
0
    else if (g.HoveredWindow == NULL)
4866
0
        g.HoverWindowUnlockedStationaryId = 0;
4867
4868
    // Update hover delay for IsItemHovered() with delays and tooltips
4869
0
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4870
0
    if (g.HoverItemDelayId != 0)
4871
0
    {
4872
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4873
0
        g.HoverItemDelayClearTimer = 0.0f;
4874
0
        g.HoverItemDelayId = 0;
4875
0
    }
4876
0
    else if (g.HoverItemDelayTimer > 0.0f)
4877
0
    {
4878
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4879
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4880
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4881
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4882
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4883
0
    }
4884
4885
    // Drag and drop
4886
0
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4887
0
    g.DragDropAcceptIdCurr = 0;
4888
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4889
0
    g.DragDropWithinSource = false;
4890
0
    g.DragDropWithinTarget = false;
4891
0
    g.DragDropHoldJustPressedId = 0;
4892
4893
    // Close popups on focus lost (currently wip/opt-in)
4894
    //if (g.IO.AppFocusLost)
4895
    //    ClosePopupsExceptModals();
4896
4897
    // Update keyboard input state
4898
0
    UpdateKeyboardInputs();
4899
4900
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4901
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4902
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4903
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4904
4905
    // Update gamepad/keyboard navigation
4906
0
    NavUpdate();
4907
4908
    // Update mouse input state
4909
0
    UpdateMouseInputs();
4910
4911
    // Undocking
4912
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4913
0
    DockContextNewFrameUpdateUndocking(&g);
4914
4915
    // Find hovered window
4916
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4917
0
    UpdateHoveredWindowAndCaptureFlags();
4918
4919
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4920
0
    UpdateMouseMovingWindowNewFrame();
4921
4922
    // Background darkening/whitening
4923
0
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4924
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4925
0
    else
4926
0
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4927
4928
0
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4929
0
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4930
4931
    // Platform IME data: reset for the frame
4932
0
    g.PlatformImeDataPrev = g.PlatformImeData;
4933
0
    g.PlatformImeData.WantVisible = false;
4934
4935
    // Mouse wheel scrolling, scale
4936
0
    UpdateMouseWheel();
4937
4938
    // Mark all windows as not visible and compact unused memory.
4939
0
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4940
0
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4941
0
    for (ImGuiWindow* window : g.Windows)
4942
0
    {
4943
0
        window->WasActive = window->Active;
4944
0
        window->Active = false;
4945
0
        window->WriteAccessed = false;
4946
0
        window->BeginCountPreviousFrame = window->BeginCount;
4947
0
        window->BeginCount = 0;
4948
4949
        // Garbage collect transient buffers of recently unused windows
4950
0
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4951
0
            GcCompactTransientWindowBuffers(window);
4952
0
    }
4953
4954
    // Garbage collect transient buffers of recently unused tables
4955
0
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4956
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4957
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4958
0
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4959
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4960
0
            TableGcCompactTransientBuffers(&table_temp_data);
4961
0
    if (g.GcCompactAll)
4962
0
        GcCompactTransientMiscBuffers();
4963
0
    g.GcCompactAll = false;
4964
4965
    // Closing the focused window restore focus to the first active root window in descending z-order
4966
0
    if (g.NavWindow && !g.NavWindow->WasActive)
4967
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4968
4969
    // No window should be open at the beginning of the frame.
4970
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4971
0
    g.CurrentWindowStack.resize(0);
4972
0
    g.BeginPopupStack.resize(0);
4973
0
    g.ItemFlagsStack.resize(0);
4974
0
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4975
0
    g.GroupStack.resize(0);
4976
4977
    // Docking
4978
0
    DockContextNewFrameUpdateDocking(&g);
4979
4980
    // [DEBUG] Update debug features
4981
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4982
0
    UpdateDebugToolItemPicker();
4983
0
    UpdateDebugToolStackQueries();
4984
0
    UpdateDebugToolFlashStyleColor();
4985
0
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4986
0
    {
4987
0
        g.DebugLocateId = 0;
4988
0
        g.DebugBreakInLocateId = false;
4989
0
    }
4990
0
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
4991
0
    {
4992
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
4993
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
4994
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
4995
0
    }
4996
0
#endif
4997
4998
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4999
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5000
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5001
0
    g.WithinFrameScopeWithImplicitWindow = true;
5002
0
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5003
0
    Begin("Debug##Default");
5004
0
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5005
5006
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5007
    // allowing to validate correct Begin/End behavior in user code.
5008
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5009
0
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5010
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5011
0
    else
5012
0
        g.DebugBeginReturnValueCullDepth = -1;
5013
0
#endif
5014
5015
0
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5016
0
}
5017
5018
// FIXME: Add a more explicit sort order in the window structure.
5019
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5020
0
{
5021
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5022
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5023
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5024
0
        return d;
5025
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5026
0
        return d;
5027
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5028
0
}
5029
5030
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5031
0
{
5032
0
    out_sorted_windows->push_back(window);
5033
0
    if (window->Active)
5034
0
    {
5035
0
        int count = window->DC.ChildWindows.Size;
5036
0
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5037
0
        for (int i = 0; i < count; i++)
5038
0
        {
5039
0
            ImGuiWindow* child = window->DC.ChildWindows[i];
5040
0
            if (child->Active)
5041
0
                AddWindowToSortBuffer(out_sorted_windows, child);
5042
0
        }
5043
0
    }
5044
0
}
5045
5046
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5047
0
{
5048
0
    ImGuiContext& g = *GImGui;
5049
0
    ImGuiViewportP* viewport = window->Viewport;
5050
0
    IM_ASSERT(viewport != NULL);
5051
0
    g.IO.MetricsRenderWindows++;
5052
0
    if (window->DrawList->_Splitter._Count > 1)
5053
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5054
0
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5055
0
    for (ImGuiWindow* child : window->DC.ChildWindows)
5056
0
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5057
0
            AddWindowToDrawData(child, layer);
5058
0
}
5059
5060
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5061
0
{
5062
0
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5063
0
}
5064
5065
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5066
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5067
0
{
5068
0
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5069
0
}
5070
5071
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5072
0
{
5073
0
    int n = builder->Layers[0]->Size;
5074
0
    int full_size = n;
5075
0
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5076
0
        full_size += builder->Layers[i]->Size;
5077
0
    builder->Layers[0]->resize(full_size);
5078
0
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5079
0
    {
5080
0
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5081
0
        if (layer->empty())
5082
0
            continue;
5083
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5084
0
        n += layer->Size;
5085
0
        layer->resize(0);
5086
0
    }
5087
0
}
5088
5089
static void InitViewportDrawData(ImGuiViewportP* viewport)
5090
0
{
5091
0
    ImGuiIO& io = ImGui::GetIO();
5092
0
    ImDrawData* draw_data = &viewport->DrawDataP;
5093
5094
0
    viewport->DrawData = draw_data; // Make publicly accessible
5095
0
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5096
0
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5097
0
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5098
0
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5099
5100
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5101
    // and to allow applications/backends to easily skip rendering.
5102
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5103
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5104
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5105
0
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5106
5107
0
    draw_data->Valid = true;
5108
0
    draw_data->CmdListsCount = 0;
5109
0
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5110
0
    draw_data->DisplayPos = viewport->Pos;
5111
0
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5112
0
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5113
0
    draw_data->OwnerViewport = viewport;
5114
0
}
5115
5116
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5117
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5118
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5119
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5120
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5121
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5122
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5123
0
{
5124
0
    ImGuiWindow* window = GetCurrentWindow();
5125
0
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5126
0
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5127
0
}
5128
5129
void ImGui::PopClipRect()
5130
0
{
5131
0
    ImGuiWindow* window = GetCurrentWindow();
5132
0
    window->DrawList->PopClipRect();
5133
0
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5134
0
}
5135
5136
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5137
0
{
5138
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5139
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5140
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5141
0
    return window;
5142
0
}
5143
5144
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5145
0
{
5146
0
    if ((col & IM_COL32_A_MASK) == 0)
5147
0
        return;
5148
5149
0
    ImGuiViewportP* viewport = window->Viewport;
5150
0
    ImRect viewport_rect = viewport->GetMainRect();
5151
5152
    // Draw behind window by moving the draw command at the FRONT of the draw list
5153
0
    {
5154
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5155
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5156
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5157
0
        draw_list->ChannelsMerge();
5158
0
        if (draw_list->CmdBuffer.Size == 0)
5159
0
            draw_list->AddDrawCmd();
5160
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5161
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5162
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5163
0
        IM_ASSERT(cmd.ElemCount == 6);
5164
0
        draw_list->CmdBuffer.pop_back();
5165
0
        draw_list->CmdBuffer.push_front(cmd);
5166
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5167
0
        draw_list->PopClipRect();
5168
0
    }
5169
5170
    // Draw over sibling docking nodes in a same docking tree
5171
0
    if (window->RootWindow->DockIsActive)
5172
0
    {
5173
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5174
0
        draw_list->ChannelsMerge();
5175
0
        if (draw_list->CmdBuffer.Size == 0)
5176
0
            draw_list->AddDrawCmd();
5177
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5178
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5179
0
        draw_list->PopClipRect();
5180
0
    }
5181
0
}
5182
5183
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5184
0
{
5185
0
    ImGuiContext& g = *GImGui;
5186
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5187
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5188
0
    {
5189
0
        ImGuiWindow* window = g.Windows[i];
5190
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5191
0
            continue;
5192
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5193
0
            break;
5194
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5195
0
            bottom_most_visible_window = window;
5196
0
    }
5197
0
    return bottom_most_visible_window;
5198
0
}
5199
5200
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5201
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5202
static void ImGui::RenderDimmedBackgrounds()
5203
0
{
5204
0
    ImGuiContext& g = *GImGui;
5205
0
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5206
0
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5207
0
        return;
5208
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5209
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5210
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5211
0
        return;
5212
5213
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5214
0
    if (dim_bg_for_modal)
5215
0
    {
5216
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5217
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5218
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5219
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5220
0
    }
5221
0
    else if (dim_bg_for_window_list)
5222
0
    {
5223
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5224
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5225
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5226
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5227
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5228
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5229
5230
        // Draw border around CTRL+Tab target window
5231
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5232
0
        ImGuiViewport* viewport = window->Viewport;
5233
0
        float distance = g.FontSize;
5234
0
        ImRect bb = window->Rect();
5235
0
        bb.Expand(distance);
5236
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5237
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5238
0
        window->DrawList->ChannelsMerge();
5239
0
        if (window->DrawList->CmdBuffer.Size == 0)
5240
0
            window->DrawList->AddDrawCmd();
5241
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5242
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5243
0
        window->DrawList->PopClipRect();
5244
0
    }
5245
5246
    // Draw dimming background on _other_ viewports than the ones our windows are in
5247
0
    for (ImGuiViewportP* viewport : g.Viewports)
5248
0
    {
5249
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5250
0
            continue;
5251
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5252
0
            continue;
5253
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5254
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5255
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5256
0
    }
5257
0
}
5258
5259
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5260
void ImGui::EndFrame()
5261
0
{
5262
0
    ImGuiContext& g = *GImGui;
5263
0
    IM_ASSERT(g.Initialized);
5264
5265
    // Don't process EndFrame() multiple times.
5266
0
    if (g.FrameCountEnded == g.FrameCount)
5267
0
        return;
5268
0
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5269
5270
0
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5271
5272
0
    ErrorCheckEndFrameSanityChecks();
5273
5274
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5275
0
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5276
0
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5277
0
    {
5278
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5279
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5280
0
        if (viewport == NULL)
5281
0
            viewport = GetMainViewport();
5282
0
        g.IO.SetPlatformImeDataFn(viewport, ime_data);
5283
0
    }
5284
5285
    // Hide implicit/fallback "Debug" window if it hasn't been used
5286
0
    g.WithinFrameScopeWithImplicitWindow = false;
5287
0
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5288
0
        g.CurrentWindow->Active = false;
5289
0
    End();
5290
5291
    // Update navigation: CTRL+Tab, wrap-around requests
5292
0
    NavEndFrame();
5293
5294
    // Update docking
5295
0
    DockContextEndFrame(&g);
5296
5297
0
    SetCurrentViewport(NULL, NULL);
5298
5299
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5300
0
    if (g.DragDropActive)
5301
0
    {
5302
0
        bool is_delivered = g.DragDropPayload.Delivery;
5303
0
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5304
0
        if (is_delivered || is_elapsed)
5305
0
            ClearDragDrop();
5306
0
    }
5307
5308
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5309
0
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5310
0
    {
5311
0
        g.DragDropWithinSource = true;
5312
0
        SetTooltip("...");
5313
0
        g.DragDropWithinSource = false;
5314
0
    }
5315
5316
    // End frame
5317
0
    g.WithinFrameScope = false;
5318
0
    g.FrameCountEnded = g.FrameCount;
5319
5320
    // Initiate moving window + handle left-click and right-click focus
5321
0
    UpdateMouseMovingWindowEndFrame();
5322
5323
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5324
0
    UpdateViewportsEndFrame();
5325
5326
    // Sort the window list so that all child windows are after their parent
5327
    // We cannot do that on FocusWindow() because children may not exist yet
5328
0
    g.WindowsTempSortBuffer.resize(0);
5329
0
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5330
0
    for (ImGuiWindow* window : g.Windows)
5331
0
    {
5332
0
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5333
0
            continue;
5334
0
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5335
0
    }
5336
5337
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5338
0
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5339
0
    g.Windows.swap(g.WindowsTempSortBuffer);
5340
0
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5341
5342
    // Unlock font atlas
5343
0
    g.IO.Fonts->Locked = false;
5344
5345
    // Clear Input data for next frame
5346
0
    g.IO.MousePosPrev = g.IO.MousePos;
5347
0
    g.IO.AppFocusLost = false;
5348
0
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5349
0
    g.IO.InputQueueCharacters.resize(0);
5350
5351
0
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5352
0
}
5353
5354
// Prepare the data for rendering so you can call GetDrawData()
5355
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5356
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5357
void ImGui::Render()
5358
0
{
5359
0
    ImGuiContext& g = *GImGui;
5360
0
    IM_ASSERT(g.Initialized);
5361
5362
0
    if (g.FrameCountEnded != g.FrameCount)
5363
0
        EndFrame();
5364
0
    if (g.FrameCountRendered == g.FrameCount)
5365
0
        return;
5366
0
    g.FrameCountRendered = g.FrameCount;
5367
5368
0
    g.IO.MetricsRenderWindows = 0;
5369
0
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5370
5371
    // Add background ImDrawList (for each active viewport)
5372
0
    for (ImGuiViewportP* viewport : g.Viewports)
5373
0
    {
5374
0
        InitViewportDrawData(viewport);
5375
0
        if (viewport->BgFgDrawLists[0] != NULL)
5376
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5377
0
    }
5378
5379
    // Draw modal/window whitening backgrounds
5380
0
    RenderDimmedBackgrounds();
5381
5382
    // Add ImDrawList to render
5383
0
    ImGuiWindow* windows_to_render_top_most[2];
5384
0
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5385
0
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5386
0
    for (ImGuiWindow* window : g.Windows)
5387
0
    {
5388
0
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5389
0
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5390
0
            AddRootWindowToDrawData(window);
5391
0
    }
5392
0
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5393
0
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5394
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5395
5396
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5397
0
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5398
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5399
5400
    // Setup ImDrawData structures for end-user
5401
0
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5402
0
    for (ImGuiViewportP* viewport : g.Viewports)
5403
0
    {
5404
0
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5405
5406
        // Add foreground ImDrawList (for each active viewport)
5407
0
        if (viewport->BgFgDrawLists[1] != NULL)
5408
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5409
5410
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5411
0
        ImDrawData* draw_data = &viewport->DrawDataP;
5412
0
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5413
0
        for (ImDrawList* draw_list : draw_data->CmdLists)
5414
0
            draw_list->_PopUnusedDrawCmd();
5415
5416
0
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5417
0
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5418
0
    }
5419
5420
0
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5421
0
}
5422
5423
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5424
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5425
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5426
0
{
5427
0
    ImGuiContext& g = *GImGui;
5428
5429
0
    const char* text_display_end;
5430
0
    if (hide_text_after_double_hash)
5431
0
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5432
0
    else
5433
0
        text_display_end = text_end;
5434
5435
0
    ImFont* font = g.Font;
5436
0
    const float font_size = g.FontSize;
5437
0
    if (text == text_display_end)
5438
0
        return ImVec2(0.0f, font_size);
5439
0
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5440
5441
    // Round
5442
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5443
    // FIXME: Investigate using ceilf or e.g.
5444
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5445
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5446
0
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5447
5448
0
    return text_size;
5449
0
}
5450
5451
// Find window given position, search front-to-back
5452
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5453
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5454
// called, aka before the next Begin(). Moving window isn't affected.
5455
static void FindHoveredWindow()
5456
0
{
5457
0
    ImGuiContext& g = *GImGui;
5458
5459
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5460
0
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5461
0
    if (g.MovingWindow)
5462
0
        g.MovingWindow->Viewport = g.MouseViewport;
5463
5464
0
    ImGuiWindow* hovered_window = NULL;
5465
0
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5466
0
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5467
0
        hovered_window = g.MovingWindow;
5468
5469
0
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5470
0
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5471
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5472
0
    {
5473
0
        ImGuiWindow* window = g.Windows[i];
5474
0
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5475
0
        if (!window->Active || window->Hidden)
5476
0
            continue;
5477
0
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5478
0
            continue;
5479
0
        IM_ASSERT(window->Viewport);
5480
0
        if (window->Viewport != g.MouseViewport)
5481
0
            continue;
5482
5483
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5484
0
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5485
0
        if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5486
0
            continue;
5487
5488
        // Support for one rectangular hole in any given window
5489
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5490
0
        if (window->HitTestHoleSize.x != 0)
5491
0
        {
5492
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5493
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5494
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5495
0
                continue;
5496
0
        }
5497
5498
0
        if (hovered_window == NULL)
5499
0
            hovered_window = window;
5500
0
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5501
0
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5502
0
            hovered_window_ignoring_moving_window = window;
5503
0
        if (hovered_window && hovered_window_ignoring_moving_window)
5504
0
            break;
5505
0
    }
5506
5507
0
    g.HoveredWindow = hovered_window;
5508
0
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5509
5510
0
    if (g.MovingWindow)
5511
0
        g.MovingWindow->Viewport = moving_window_viewport;
5512
0
}
5513
5514
bool ImGui::IsItemActive()
5515
0
{
5516
0
    ImGuiContext& g = *GImGui;
5517
0
    if (g.ActiveId)
5518
0
        return g.ActiveId == g.LastItemData.ID;
5519
0
    return false;
5520
0
}
5521
5522
bool ImGui::IsItemActivated()
5523
0
{
5524
0
    ImGuiContext& g = *GImGui;
5525
0
    if (g.ActiveId)
5526
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5527
0
            return true;
5528
0
    return false;
5529
0
}
5530
5531
bool ImGui::IsItemDeactivated()
5532
0
{
5533
0
    ImGuiContext& g = *GImGui;
5534
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5535
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5536
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5537
0
}
5538
5539
bool ImGui::IsItemDeactivatedAfterEdit()
5540
0
{
5541
0
    ImGuiContext& g = *GImGui;
5542
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5543
0
}
5544
5545
// == GetItemID() == GetFocusID()
5546
bool ImGui::IsItemFocused()
5547
0
{
5548
0
    ImGuiContext& g = *GImGui;
5549
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5550
0
        return false;
5551
5552
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5553
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5554
0
    ImGuiWindow* window = g.CurrentWindow;
5555
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5556
0
        return false;
5557
5558
0
    return true;
5559
0
}
5560
5561
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5562
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5563
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5564
0
{
5565
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5566
0
}
5567
5568
bool ImGui::IsItemToggledOpen()
5569
0
{
5570
0
    ImGuiContext& g = *GImGui;
5571
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5572
0
}
5573
5574
bool ImGui::IsItemToggledSelection()
5575
0
{
5576
0
    ImGuiContext& g = *GImGui;
5577
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5578
0
}
5579
5580
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5581
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5582
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5583
bool ImGui::IsAnyItemHovered()
5584
0
{
5585
0
    ImGuiContext& g = *GImGui;
5586
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5587
0
}
5588
5589
bool ImGui::IsAnyItemActive()
5590
0
{
5591
0
    ImGuiContext& g = *GImGui;
5592
0
    return g.ActiveId != 0;
5593
0
}
5594
5595
bool ImGui::IsAnyItemFocused()
5596
0
{
5597
0
    ImGuiContext& g = *GImGui;
5598
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5599
0
}
5600
5601
bool ImGui::IsItemVisible()
5602
0
{
5603
0
    ImGuiContext& g = *GImGui;
5604
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5605
0
}
5606
5607
bool ImGui::IsItemEdited()
5608
0
{
5609
0
    ImGuiContext& g = *GImGui;
5610
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5611
0
}
5612
5613
// Allow next item to be overlapped by subsequent items.
5614
// This works by requiring HoveredId to match for two subsequent frames,
5615
// so if a following items overwrite it our interactions will naturally be disabled.
5616
void ImGui::SetNextItemAllowOverlap()
5617
0
{
5618
0
    ImGuiContext& g = *GImGui;
5619
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5620
0
}
5621
5622
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5623
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5624
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5625
void ImGui::SetItemAllowOverlap()
5626
{
5627
    ImGuiContext& g = *GImGui;
5628
    ImGuiID id = g.LastItemData.ID;
5629
    if (g.HoveredId == id)
5630
        g.HoveredIdAllowOverlap = true;
5631
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5632
        g.ActiveIdAllowOverlap = true;
5633
}
5634
#endif
5635
5636
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5637
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5638
0
{
5639
0
    ImGuiContext& g = *GImGui;
5640
0
    IM_ASSERT(g.ActiveId != 0);
5641
0
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5642
0
    g.ActiveIdUsingAllKeyboardKeys = true;
5643
0
    NavMoveRequestCancel();
5644
0
}
5645
5646
ImGuiID ImGui::GetItemID()
5647
0
{
5648
0
    ImGuiContext& g = *GImGui;
5649
0
    return g.LastItemData.ID;
5650
0
}
5651
5652
ImVec2 ImGui::GetItemRectMin()
5653
0
{
5654
0
    ImGuiContext& g = *GImGui;
5655
0
    return g.LastItemData.Rect.Min;
5656
0
}
5657
5658
ImVec2 ImGui::GetItemRectMax()
5659
0
{
5660
0
    ImGuiContext& g = *GImGui;
5661
0
    return g.LastItemData.Rect.Max;
5662
0
}
5663
5664
ImVec2 ImGui::GetItemRectSize()
5665
0
{
5666
0
    ImGuiContext& g = *GImGui;
5667
0
    return g.LastItemData.Rect.GetSize();
5668
0
}
5669
5670
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5671
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5672
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5673
0
{
5674
0
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5675
0
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5676
0
}
5677
5678
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5679
0
{
5680
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5681
0
}
5682
5683
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5684
0
{
5685
0
    ImGuiContext& g = *GImGui;
5686
0
    ImGuiWindow* parent_window = g.CurrentWindow;
5687
0
    IM_ASSERT(id != 0);
5688
5689
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5690
0
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle;
5691
0
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5692
0
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5693
0
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5694
0
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5695
0
    {
5696
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5697
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5698
0
    }
5699
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5700
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5701
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5702
#endif
5703
0
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5704
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5705
0
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5706
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5707
5708
    // Set window flags
5709
0
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5710
0
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5711
0
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5712
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5713
0
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5714
0
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5715
5716
    // Special framed style
5717
0
    if (child_flags & ImGuiChildFlags_FrameStyle)
5718
0
    {
5719
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5720
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5721
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5722
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5723
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5724
0
        window_flags |= ImGuiWindowFlags_NoMove;
5725
0
    }
5726
5727
    // Forward child flags
5728
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5729
0
    g.NextWindowData.ChildFlags = child_flags;
5730
5731
    // Forward size
5732
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5733
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5734
0
    const ImVec2 size_avail = GetContentRegionAvail();
5735
0
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5736
0
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5737
0
    SetNextWindowSize(size);
5738
5739
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5740
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5741
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5742
0
    const char* temp_window_name;
5743
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5744
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5745
    else*/
5746
0
    if (name)
5747
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5748
0
    else
5749
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5750
5751
    // Set style
5752
0
    const float backup_border_size = g.Style.ChildBorderSize;
5753
0
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5754
0
        g.Style.ChildBorderSize = 0.0f;
5755
5756
    // Begin into window
5757
0
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5758
5759
    // Restore style
5760
0
    g.Style.ChildBorderSize = backup_border_size;
5761
0
    if (child_flags & ImGuiChildFlags_FrameStyle)
5762
0
    {
5763
0
        PopStyleVar(3);
5764
0
        PopStyleColor();
5765
0
    }
5766
5767
0
    ImGuiWindow* child_window = g.CurrentWindow;
5768
0
    child_window->ChildId = id;
5769
5770
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5771
    // While this is not really documented/defined, it seems that the expected thing to do.
5772
0
    if (child_window->BeginCount == 1)
5773
0
        parent_window->DC.CursorPos = child_window->Pos;
5774
5775
    // Process navigation-in immediately so NavInit can run on first frame
5776
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5777
0
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5778
0
    if (g.ActiveId == temp_id_for_activation)
5779
0
        ClearActiveID();
5780
0
    if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5781
0
    {
5782
0
        FocusWindow(child_window);
5783
0
        NavInitWindow(child_window, false);
5784
0
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5785
0
        g.ActiveIdSource = g.NavInputSource;
5786
0
    }
5787
0
    return ret;
5788
0
}
5789
5790
void ImGui::EndChild()
5791
0
{
5792
0
    ImGuiContext& g = *GImGui;
5793
0
    ImGuiWindow* child_window = g.CurrentWindow;
5794
5795
0
    IM_ASSERT(g.WithinEndChild == false);
5796
0
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5797
5798
0
    g.WithinEndChild = true;
5799
0
    ImVec2 child_size = child_window->Size;
5800
0
    End();
5801
0
    if (child_window->BeginCount == 1)
5802
0
    {
5803
0
        ImGuiWindow* parent_window = g.CurrentWindow;
5804
0
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5805
0
        ItemSize(child_size);
5806
0
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5807
0
        {
5808
0
            ItemAdd(bb, child_window->ChildId);
5809
0
            RenderNavHighlight(bb, child_window->ChildId);
5810
5811
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5812
0
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5813
0
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5814
0
        }
5815
0
        else
5816
0
        {
5817
            // Not navigable into
5818
0
            ItemAdd(bb, 0);
5819
5820
            // But when flattened we directly reach items, adjust active layer mask accordingly
5821
0
            if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5822
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5823
0
        }
5824
0
        if (g.HoveredWindow == child_window)
5825
0
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5826
0
    }
5827
0
    g.WithinEndChild = false;
5828
0
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5829
0
}
5830
5831
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5832
0
{
5833
0
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5834
0
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5835
0
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5836
0
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5837
0
}
5838
5839
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5840
0
{
5841
0
    ImGuiContext& g = *GImGui;
5842
0
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5843
0
}
5844
5845
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5846
0
{
5847
0
    ImGuiID id = ImHashStr(name);
5848
0
    return FindWindowByID(id);
5849
0
}
5850
5851
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5852
0
{
5853
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5854
0
    window->ViewportPos = main_viewport->Pos;
5855
0
    if (settings->ViewportId)
5856
0
    {
5857
0
        window->ViewportId = settings->ViewportId;
5858
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5859
0
    }
5860
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5861
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5862
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5863
0
    window->Collapsed = settings->Collapsed;
5864
0
    window->DockId = settings->DockId;
5865
0
    window->DockOrder = settings->DockOrder;
5866
0
}
5867
5868
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5869
0
{
5870
0
    ImGuiContext& g = *GImGui;
5871
5872
0
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5873
0
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5874
0
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5875
0
    {
5876
0
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5877
0
        g.WindowsFocusOrder.push_back(window);
5878
0
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5879
0
    }
5880
0
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5881
0
    {
5882
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5883
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5884
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5885
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5886
0
        window->FocusOrder = -1;
5887
0
    }
5888
0
    window->IsExplicitChild = new_is_explicit_child;
5889
0
}
5890
5891
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5892
0
{
5893
    // Initial window state with e.g. default/arbitrary window position
5894
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5895
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5896
0
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5897
0
    window->Size = window->SizeFull = ImVec2(0, 0);
5898
0
    window->ViewportPos = main_viewport->Pos;
5899
0
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5900
5901
0
    if (settings != NULL)
5902
0
    {
5903
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5904
0
        ApplyWindowSettings(window, settings);
5905
0
    }
5906
0
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5907
5908
0
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5909
0
    {
5910
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5911
0
        window->AutoFitOnlyGrows = false;
5912
0
    }
5913
0
    else
5914
0
    {
5915
0
        if (window->Size.x <= 0.0f)
5916
0
            window->AutoFitFramesX = 2;
5917
0
        if (window->Size.y <= 0.0f)
5918
0
            window->AutoFitFramesY = 2;
5919
0
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5920
0
    }
5921
0
}
5922
5923
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5924
0
{
5925
    // Create window the first time
5926
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5927
0
    ImGuiContext& g = *GImGui;
5928
0
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5929
0
    window->Flags = flags;
5930
0
    g.WindowsById.SetVoidPtr(window->ID, window);
5931
5932
0
    ImGuiWindowSettings* settings = NULL;
5933
0
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5934
0
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5935
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5936
5937
0
    InitOrLoadWindowSettings(window, settings);
5938
5939
0
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5940
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5941
0
    else
5942
0
        g.Windows.push_back(window);
5943
5944
0
    return window;
5945
0
}
5946
5947
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5948
0
{
5949
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5950
0
}
5951
5952
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5953
0
{
5954
0
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5955
0
}
5956
5957
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5958
0
{
5959
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5960
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
5961
    // Perhaps should tend further a neater test for this.
5962
0
    ImGuiContext& g = *GImGui;
5963
0
    ImVec2 size_min;
5964
0
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
5965
0
    {
5966
0
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5967
0
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5968
0
    }
5969
0
    else
5970
0
    {
5971
0
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
5972
0
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
5973
0
    }
5974
5975
    // Reduce artifacts with very small windows
5976
0
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5977
0
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
5978
0
    return size_min;
5979
0
}
5980
5981
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5982
0
{
5983
0
    ImGuiContext& g = *GImGui;
5984
0
    ImVec2 new_size = size_desired;
5985
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5986
0
    {
5987
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
5988
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5989
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5990
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5991
0
        if (g.NextWindowData.SizeCallback)
5992
0
        {
5993
0
            ImGuiSizeCallbackData data;
5994
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5995
0
            data.Pos = window->Pos;
5996
0
            data.CurrentSize = window->SizeFull;
5997
0
            data.DesiredSize = new_size;
5998
0
            g.NextWindowData.SizeCallback(&data);
5999
0
            new_size = data.DesiredSize;
6000
0
        }
6001
0
        new_size.x = IM_TRUNC(new_size.x);
6002
0
        new_size.y = IM_TRUNC(new_size.y);
6003
0
    }
6004
6005
    // Minimum size
6006
0
    ImVec2 size_min = CalcWindowMinSize(window);
6007
0
    return ImMax(new_size, size_min);
6008
0
}
6009
6010
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6011
0
{
6012
0
    bool preserve_old_content_sizes = false;
6013
0
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6014
0
        preserve_old_content_sizes = true;
6015
0
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6016
0
        preserve_old_content_sizes = true;
6017
0
    if (preserve_old_content_sizes)
6018
0
    {
6019
0
        *content_size_current = window->ContentSize;
6020
0
        *content_size_ideal = window->ContentSizeIdeal;
6021
0
        return;
6022
0
    }
6023
6024
0
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6025
0
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6026
0
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6027
0
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6028
0
}
6029
6030
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6031
0
{
6032
0
    ImGuiContext& g = *GImGui;
6033
0
    ImGuiStyle& style = g.Style;
6034
0
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6035
0
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6036
0
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6037
0
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6038
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6039
0
    {
6040
        // Tooltip always resize
6041
0
        return size_desired;
6042
0
    }
6043
0
    else
6044
0
    {
6045
        // Maximum window size is determined by the viewport size or monitor size
6046
0
        ImVec2 size_min = CalcWindowMinSize(window);
6047
0
        ImVec2 size_max = (window->ViewportOwned || ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))) ? ImVec2(FLT_MAX, FLT_MAX) : ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6048
0
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6049
0
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0)
6050
0
            size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6051
0
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6052
6053
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6054
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6055
0
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6056
0
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6057
0
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6058
0
        if (will_have_scrollbar_x)
6059
0
            size_auto_fit.y += style.ScrollbarSize;
6060
0
        if (will_have_scrollbar_y)
6061
0
            size_auto_fit.x += style.ScrollbarSize;
6062
0
        return size_auto_fit;
6063
0
    }
6064
0
}
6065
6066
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6067
0
{
6068
0
    ImVec2 size_contents_current;
6069
0
    ImVec2 size_contents_ideal;
6070
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6071
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6072
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6073
0
    return size_final;
6074
0
}
6075
6076
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6077
0
{
6078
0
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6079
0
        return ImGuiCol_PopupBg;
6080
0
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6081
0
        return ImGuiCol_ChildBg;
6082
0
    return ImGuiCol_WindowBg;
6083
0
}
6084
6085
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6086
0
{
6087
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6088
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6089
0
    ImVec2 size_expected = pos_max - pos_min;
6090
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6091
0
    *out_pos = pos_min;
6092
0
    if (corner_norm.x == 0.0f)
6093
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6094
0
    if (corner_norm.y == 0.0f)
6095
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6096
0
    *out_size = size_constrained;
6097
0
}
6098
6099
// Data for resizing from resize grip / corner
6100
struct ImGuiResizeGripDef
6101
{
6102
    ImVec2  CornerPosN;
6103
    ImVec2  InnerDir;
6104
    int     AngleMin12, AngleMax12;
6105
};
6106
static const ImGuiResizeGripDef resize_grip_def[4] =
6107
{
6108
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6109
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6110
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6111
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6112
};
6113
6114
// Data for resizing from borders
6115
struct ImGuiResizeBorderDef
6116
{
6117
    ImVec2  InnerDir;               // Normal toward inside
6118
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6119
    float   OuterAngle;             // Angle toward outside
6120
};
6121
static const ImGuiResizeBorderDef resize_border_def[4] =
6122
{
6123
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6124
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6125
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6126
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6127
};
6128
6129
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6130
0
{
6131
0
    ImRect rect = window->Rect();
6132
0
    if (thickness == 0.0f)
6133
0
        rect.Max -= ImVec2(1, 1);
6134
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6135
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6136
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6137
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6138
0
    IM_ASSERT(0);
6139
0
    return ImRect();
6140
0
}
6141
6142
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6143
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6144
0
{
6145
0
    IM_ASSERT(n >= 0 && n < 4);
6146
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6147
0
    id = ImHashStr("#RESIZE", 0, id);
6148
0
    id = ImHashData(&n, sizeof(int), id);
6149
0
    return id;
6150
0
}
6151
6152
// Borders (Left, Right, Up, Down)
6153
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6154
0
{
6155
0
    IM_ASSERT(dir >= 0 && dir < 4);
6156
0
    int n = (int)dir + 4;
6157
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6158
0
    id = ImHashStr("#RESIZE", 0, id);
6159
0
    id = ImHashData(&n, sizeof(int), id);
6160
0
    return id;
6161
0
}
6162
6163
// Handle resize for: Resize Grips, Borders, Gamepad
6164
// Return true when using auto-fit (double-click on resize grip)
6165
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6166
0
{
6167
0
    ImGuiContext& g = *GImGui;
6168
0
    ImGuiWindowFlags flags = window->Flags;
6169
6170
0
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6171
0
        return false;
6172
0
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6173
0
        return false;
6174
6175
0
    int ret_auto_fit_mask = 0x00;
6176
0
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6177
0
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6178
0
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6179
6180
0
    ImRect clamp_rect = visibility_rect;
6181
0
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6182
0
    if (window_move_from_title_bar)
6183
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6184
6185
0
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6186
0
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6187
6188
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6189
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6190
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6191
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6192
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6193
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6194
0
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6195
0
    if (clip_with_viewport_rect)
6196
0
        window->ClipRect = window->Viewport->GetMainRect();
6197
6198
    // Resize grips and borders are on layer 1
6199
0
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6200
6201
    // Manual resize grips
6202
0
    PushID("#RESIZE");
6203
0
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6204
0
    {
6205
0
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6206
0
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6207
6208
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6209
0
        bool hovered, held;
6210
0
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6211
0
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6212
0
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6213
0
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6214
0
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6215
0
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6216
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6217
0
        if (hovered || held)
6218
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6219
6220
0
        if (held && g.IO.MouseDoubleClicked[0])
6221
0
        {
6222
            // Auto-fit when double-clicking
6223
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6224
0
            ret_auto_fit_mask = 0x03; // Both axises
6225
0
            ClearActiveID();
6226
0
        }
6227
0
        else if (held)
6228
0
        {
6229
            // Resize from any of the four corners
6230
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6231
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6232
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6233
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6234
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6235
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6236
0
        }
6237
6238
        // Only lower-left grip is visible before hovering/activating
6239
0
        if (resize_grip_n == 0 || held || hovered)
6240
0
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6241
0
    }
6242
6243
0
    int resize_border_mask = 0x00;
6244
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6245
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6246
0
    else
6247
0
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6248
0
    for (int border_n = 0; border_n < 4; border_n++)
6249
0
    {
6250
0
        if ((resize_border_mask & (1 << border_n)) == 0)
6251
0
            continue;
6252
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6253
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6254
6255
0
        bool hovered, held;
6256
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6257
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6258
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6259
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6260
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6261
0
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6262
0
            hovered = false;
6263
0
        if (hovered || held)
6264
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6265
0
        if (held && g.IO.MouseDoubleClicked[0])
6266
0
        {
6267
            // Double-clicking bottom or right border auto-fit on this axis
6268
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6269
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6270
0
            {
6271
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6272
0
                ret_auto_fit_mask |= (1 << axis);
6273
0
                hovered = held = false; // So border doesn't show highlighted at new position
6274
0
            }
6275
0
            ClearActiveID();
6276
0
        }
6277
0
        else if (held)
6278
0
        {
6279
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6280
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6281
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6282
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6283
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6284
0
            {
6285
0
                g.WindowResizeBorderExpectedRect = border_rect;
6286
0
                g.WindowResizeRelativeMode = false;
6287
0
            }
6288
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6289
0
                g.WindowResizeRelativeMode = true;
6290
6291
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6292
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6293
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6294
6295
            // Use absolute mode position
6296
0
            ImVec2 border_target = window->Pos;
6297
0
            border_target[axis] = border_target_abs_mode_for_axis;
6298
6299
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6300
0
            bool ignore_resize = false;
6301
0
            if (g.WindowResizeRelativeMode)
6302
0
            {
6303
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6304
0
                border_target[axis] = border_target_rel_mode_for_axis;
6305
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6306
0
                    ignore_resize = true;
6307
0
            }
6308
6309
            // Clamp, apply
6310
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6311
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6312
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6313
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6314
0
            {
6315
0
                ImGuiWindowFlags parent_flags = window->ParentWindow->Flags;
6316
0
                ImRect border_limit_rect = window->ParentWindow->InnerRect;
6317
0
                border_limit_rect.Expand(ImVec2(-ImMax(window->WindowPadding.x, window->WindowBorderSize), -ImMax(window->WindowPadding.y, window->WindowBorderSize)));
6318
0
                if ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar))
6319
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6320
0
                if (parent_flags & ImGuiWindowFlags_NoScrollbar)
6321
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6322
0
            }
6323
0
            if (!ignore_resize)
6324
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6325
0
        }
6326
0
        if (hovered)
6327
0
            *border_hovered = border_n;
6328
0
        if (held)
6329
0
            *border_held = border_n;
6330
0
    }
6331
0
    PopID();
6332
6333
    // Restore nav layer
6334
0
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6335
6336
    // Navigation resize (keyboard/gamepad)
6337
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6338
    // Not even sure the callback works here.
6339
0
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6340
0
    {
6341
0
        ImVec2 nav_resize_dir;
6342
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6343
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6344
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6345
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6346
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6347
0
        {
6348
0
            const float NAV_RESIZE_SPEED = 600.0f;
6349
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6350
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6351
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6352
0
            g.NavWindowingToggleLayer = false;
6353
0
            g.NavDisableMouseHover = true;
6354
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6355
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6356
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6357
0
            {
6358
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6359
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6360
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6361
0
            }
6362
0
        }
6363
0
    }
6364
6365
    // Apply back modified position/size to window
6366
0
    const ImVec2 curr_pos = window->Pos;
6367
0
    const ImVec2 curr_size = window->SizeFull;
6368
0
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6369
0
        window->Size.x = window->SizeFull.x = size_target.x;
6370
0
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6371
0
        window->Size.y = window->SizeFull.y = size_target.y;
6372
0
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6373
0
        window->Pos.x = ImTrunc(pos_target.x);
6374
0
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6375
0
        window->Pos.y = ImTrunc(pos_target.y);
6376
0
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6377
0
        MarkIniSettingsDirty(window);
6378
6379
    // Recalculate next expected border expected coordinates
6380
0
    if (*border_held != -1)
6381
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6382
6383
0
    return ret_auto_fit_mask;
6384
0
}
6385
6386
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6387
0
{
6388
0
    ImGuiContext& g = *GImGui;
6389
0
    ImVec2 size_for_clamping = window->Size;
6390
0
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6391
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6392
0
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6393
0
}
6394
6395
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6396
0
{
6397
0
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6398
0
    const float rounding = window->WindowRounding;
6399
0
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6400
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6401
0
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6402
0
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6403
0
}
6404
6405
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6406
0
{
6407
0
    ImGuiContext& g = *GImGui;
6408
0
    const float border_size = window->WindowBorderSize;
6409
0
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6410
0
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6411
0
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6412
0
    else if (border_size > 0.0f)
6413
0
    {
6414
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6415
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6416
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6417
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6418
0
    }
6419
0
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6420
0
    {
6421
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6422
0
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6423
0
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6424
0
    }
6425
0
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6426
0
    {
6427
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6428
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6429
0
    }
6430
0
}
6431
6432
// Draw background and borders
6433
// Draw and handle scrollbars
6434
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6435
0
{
6436
0
    ImGuiContext& g = *GImGui;
6437
0
    ImGuiStyle& style = g.Style;
6438
0
    ImGuiWindowFlags flags = window->Flags;
6439
6440
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6441
0
    IM_ASSERT(window->BeginCount == 0);
6442
0
    window->SkipItems = false;
6443
6444
    // Draw window + handle manual resize
6445
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6446
0
    const float window_rounding = window->WindowRounding;
6447
0
    const float window_border_size = window->WindowBorderSize;
6448
0
    if (window->Collapsed)
6449
0
    {
6450
        // Title bar only
6451
0
        const float backup_border_size = style.FrameBorderSize;
6452
0
        g.Style.FrameBorderSize = window->WindowBorderSize;
6453
0
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6454
0
        if (window->ViewportOwned)
6455
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6456
0
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6457
0
        g.Style.FrameBorderSize = backup_border_size;
6458
0
    }
6459
0
    else
6460
0
    {
6461
        // Window background
6462
0
        if (!(flags & ImGuiWindowFlags_NoBackground))
6463
0
        {
6464
0
            bool is_docking_transparent_payload = false;
6465
0
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6466
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6467
0
                    is_docking_transparent_payload = true;
6468
6469
0
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6470
0
            if (window->ViewportOwned)
6471
0
            {
6472
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6473
0
                if (is_docking_transparent_payload)
6474
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6475
0
            }
6476
0
            else
6477
0
            {
6478
                // Adjust alpha. For docking
6479
0
                bool override_alpha = false;
6480
0
                float alpha = 1.0f;
6481
0
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6482
0
                {
6483
0
                    alpha = g.NextWindowData.BgAlphaVal;
6484
0
                    override_alpha = true;
6485
0
                }
6486
0
                if (is_docking_transparent_payload)
6487
0
                {
6488
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6489
0
                    override_alpha = true;
6490
0
                }
6491
0
                if (override_alpha)
6492
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6493
0
            }
6494
6495
            // Render, for docked windows and host windows we ensure bg goes before decorations
6496
0
            if (window->DockIsActive)
6497
0
                window->DockNode->LastBgColor = bg_col;
6498
0
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6499
0
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6500
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6501
0
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6502
0
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6503
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6504
0
        }
6505
0
        if (window->DockIsActive)
6506
0
            window->DockNode->IsBgDrawnThisFrame = true;
6507
6508
        // Title bar
6509
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6510
        // in order for their pos/size to be matching their undocking state.)
6511
0
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6512
0
        {
6513
0
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6514
0
            if (window->ViewportOwned)
6515
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6516
0
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6517
0
        }
6518
6519
        // Menu bar
6520
0
        if (flags & ImGuiWindowFlags_MenuBar)
6521
0
        {
6522
0
            ImRect menu_bar_rect = window->MenuBarRect();
6523
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6524
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6525
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6526
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6527
0
        }
6528
6529
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6530
0
        ImGuiDockNode* node = window->DockNode;
6531
0
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6532
0
        {
6533
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6534
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6535
0
            ImVec2 p = node->Pos;
6536
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6537
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6538
0
            KeepAliveID(unhide_id);
6539
0
            bool hovered, held;
6540
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6541
0
                node->WantHiddenTabBarToggle = true;
6542
0
            else if (held && IsMouseDragging(0))
6543
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6544
6545
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6546
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6547
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6548
0
        }
6549
6550
        // Scrollbars
6551
0
        if (window->ScrollbarX)
6552
0
            Scrollbar(ImGuiAxis_X);
6553
0
        if (window->ScrollbarY)
6554
0
            Scrollbar(ImGuiAxis_Y);
6555
6556
        // Render resize grips (after their input handling so we don't have a frame of latency)
6557
0
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6558
0
        {
6559
0
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6560
0
            {
6561
0
                const ImU32 col = resize_grip_col[resize_grip_n];
6562
0
                if ((col & IM_COL32_A_MASK) == 0)
6563
0
                    continue;
6564
0
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6565
0
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6566
0
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6567
0
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6568
0
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6569
0
                window->DrawList->PathFillConvex(col);
6570
0
            }
6571
0
        }
6572
6573
        // Borders (for dock node host they will be rendered over after the tab bar)
6574
0
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6575
0
            RenderWindowOuterBorders(window);
6576
0
    }
6577
0
}
6578
6579
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6580
// Render title text, collapse button, close button
6581
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6582
0
{
6583
0
    ImGuiContext& g = *GImGui;
6584
0
    ImGuiStyle& style = g.Style;
6585
0
    ImGuiWindowFlags flags = window->Flags;
6586
6587
0
    const bool has_close_button = (p_open != NULL);
6588
0
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6589
6590
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6591
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6592
0
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6593
0
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6594
0
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6595
6596
    // Layout buttons
6597
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6598
0
    float pad_l = style.FramePadding.x;
6599
0
    float pad_r = style.FramePadding.x;
6600
0
    float button_sz = g.FontSize;
6601
0
    ImVec2 close_button_pos;
6602
0
    ImVec2 collapse_button_pos;
6603
0
    if (has_close_button)
6604
0
    {
6605
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6606
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6607
0
    }
6608
0
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6609
0
    {
6610
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6611
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6612
0
    }
6613
0
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6614
0
    {
6615
0
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6616
0
        pad_l += button_sz + style.ItemInnerSpacing.x;
6617
0
    }
6618
6619
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6620
0
    if (has_collapse_button)
6621
0
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6622
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6623
6624
    // Close button
6625
0
    if (has_close_button)
6626
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6627
0
            *p_open = false;
6628
6629
0
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6630
0
    g.CurrentItemFlags = item_flags_backup;
6631
6632
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6633
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6634
0
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6635
0
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6636
6637
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6638
    // while uncentered title text will still reach edges correctly.
6639
0
    if (pad_l > style.FramePadding.x)
6640
0
        pad_l += g.Style.ItemInnerSpacing.x;
6641
0
    if (pad_r > style.FramePadding.x)
6642
0
        pad_r += g.Style.ItemInnerSpacing.x;
6643
0
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6644
0
    {
6645
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6646
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6647
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6648
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6649
0
    }
6650
6651
0
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6652
0
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6653
0
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6654
0
    {
6655
0
        ImVec2 marker_pos;
6656
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6657
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6658
0
        if (marker_pos.x > layout_r.Min.x)
6659
0
        {
6660
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6661
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6662
0
        }
6663
0
    }
6664
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6665
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6666
0
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6667
0
}
6668
6669
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6670
0
{
6671
0
    window->ParentWindow = parent_window;
6672
0
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6673
0
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6674
0
    {
6675
0
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6676
0
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6677
0
            window->RootWindow = parent_window->RootWindow;
6678
0
    }
6679
0
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6680
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6681
0
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6682
0
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6683
0
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6684
0
    {
6685
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6686
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6687
0
    }
6688
0
}
6689
6690
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6691
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6692
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6693
// - WindowA            // FindBlockingModal() returns Modal1
6694
//   - WindowB          //                  .. returns Modal1
6695
//   - Modal1           //                  .. returns Modal2
6696
//      - WindowC       //                  .. returns Modal2
6697
//          - WindowD   //                  .. returns Modal2
6698
//          - Modal2    //                  .. returns Modal2
6699
//            - WindowE //                  .. returns NULL
6700
// Notes:
6701
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6702
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6703
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6704
0
{
6705
0
    ImGuiContext& g = *GImGui;
6706
0
    if (g.OpenPopupStack.Size <= 0)
6707
0
        return NULL;
6708
6709
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6710
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6711
0
    {
6712
0
        ImGuiWindow* popup_window = popup_data.Window;
6713
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6714
0
            continue;
6715
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6716
0
            continue;
6717
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6718
0
            return popup_window;
6719
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6720
0
            continue;
6721
0
        return popup_window;                                        // Place window right below first block modal
6722
0
    }
6723
0
    return NULL;
6724
0
}
6725
6726
// Push a new Dear ImGui window to add widgets to.
6727
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6728
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6729
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6730
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6731
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6732
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6733
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6734
0
{
6735
0
    ImGuiContext& g = *GImGui;
6736
0
    const ImGuiStyle& style = g.Style;
6737
0
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6738
0
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6739
0
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6740
6741
    // Find or create
6742
0
    ImGuiWindow* window = FindWindowByName(name);
6743
0
    const bool window_just_created = (window == NULL);
6744
0
    if (window_just_created)
6745
0
        window = CreateNewWindow(name, flags);
6746
6747
    // [DEBUG] Debug break requested by user
6748
0
    if (g.DebugBreakInWindow == window->ID)
6749
0
        IM_DEBUG_BREAK();
6750
6751
    // Automatically disable manual moving/resizing when NoInputs is set
6752
0
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6753
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6754
6755
0
    if (flags & ImGuiWindowFlags_NavFlattened)
6756
0
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6757
6758
0
    const int current_frame = g.FrameCount;
6759
0
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6760
0
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6761
6762
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6763
0
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6764
0
    if (flags & ImGuiWindowFlags_Popup)
6765
0
    {
6766
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6767
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6768
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6769
0
    }
6770
6771
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6772
0
    const bool window_was_appearing = window->Appearing;
6773
0
    if (first_begin_of_the_frame)
6774
0
    {
6775
0
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6776
0
        window->Appearing = window_just_activated_by_user;
6777
0
        if (window->Appearing)
6778
0
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6779
0
        window->FlagsPreviousFrame = window->Flags;
6780
0
        window->Flags = (ImGuiWindowFlags)flags;
6781
0
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6782
0
        window->LastFrameActive = current_frame;
6783
0
        window->LastTimeActive = (float)g.Time;
6784
0
        window->BeginOrderWithinParent = 0;
6785
0
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6786
0
    }
6787
0
    else
6788
0
    {
6789
0
        flags = window->Flags;
6790
0
    }
6791
6792
    // Docking
6793
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6794
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6795
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6796
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6797
0
    if (first_begin_of_the_frame)
6798
0
    {
6799
0
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6800
0
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6801
0
        bool dock_node_was_visible = window->DockNodeIsVisible;
6802
0
        bool dock_tab_was_visible = window->DockTabIsVisible;
6803
0
        if (has_dock_node || new_auto_dock_node)
6804
0
        {
6805
0
            BeginDocked(window, p_open);
6806
0
            flags = window->Flags;
6807
0
            if (window->DockIsActive)
6808
0
            {
6809
0
                IM_ASSERT(window->DockNode != NULL);
6810
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6811
0
            }
6812
6813
            // Amend the Appearing flag
6814
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6815
0
            {
6816
0
                window->Appearing = true;
6817
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6818
0
            }
6819
0
        }
6820
0
        else
6821
0
        {
6822
0
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6823
0
        }
6824
0
    }
6825
6826
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6827
0
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6828
0
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6829
0
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6830
6831
    // We allow window memory to be compacted so recreate the base stack when needed.
6832
0
    if (window->IDStack.Size == 0)
6833
0
        window->IDStack.push_back(window->ID);
6834
6835
    // Add to stack
6836
0
    g.CurrentWindow = window;
6837
0
    ImGuiWindowStackData window_stack_data;
6838
0
    window_stack_data.Window = window;
6839
0
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6840
0
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6841
0
    g.CurrentWindowStack.push_back(window_stack_data);
6842
0
    if (flags & ImGuiWindowFlags_ChildMenu)
6843
0
        g.BeginMenuDepth++;
6844
6845
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6846
0
    if (first_begin_of_the_frame)
6847
0
    {
6848
0
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6849
0
        window->ParentWindowInBeginStack = parent_window_in_stack;
6850
6851
        // Focus route
6852
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
6853
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
6854
0
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
6855
0
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
6856
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
6857
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
6858
6859
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
6860
0
        if (window->WindowClass.FocusRouteParentWindowId != 0)
6861
0
        {
6862
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
6863
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
6864
0
        }
6865
0
    }
6866
6867
    // Add to focus scope stack
6868
0
    PushFocusScope((flags & ImGuiWindowFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
6869
0
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6870
6871
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
6872
0
    if (flags & ImGuiWindowFlags_Popup)
6873
0
    {
6874
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6875
0
        popup_ref.Window = window;
6876
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6877
0
        g.BeginPopupStack.push_back(popup_ref);
6878
0
        window->PopupId = popup_ref.PopupId;
6879
0
    }
6880
6881
    // Process SetNextWindow***() calls
6882
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6883
0
    bool window_pos_set_by_api = false;
6884
0
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6885
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6886
0
    {
6887
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6888
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6889
0
        {
6890
            // May be processed on the next frame if this is our first frame and we are measuring size
6891
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6892
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6893
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6894
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6895
0
        }
6896
0
        else
6897
0
        {
6898
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6899
0
        }
6900
0
    }
6901
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6902
0
    {
6903
0
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6904
0
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6905
0
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6906
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
6907
0
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6908
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
6909
0
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6910
0
    }
6911
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6912
0
    {
6913
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6914
0
        {
6915
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6916
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6917
0
        }
6918
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6919
0
        {
6920
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6921
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6922
0
        }
6923
0
    }
6924
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6925
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6926
0
    else if (first_begin_of_the_frame)
6927
0
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6928
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6929
0
        window->WindowClass = g.NextWindowData.WindowClass;
6930
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6931
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6932
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6933
0
        FocusWindow(window);
6934
0
    if (window->Appearing)
6935
0
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6936
6937
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6938
0
    g.CurrentWindow = NULL;
6939
6940
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6941
0
    if (first_begin_of_the_frame)
6942
0
    {
6943
        // Initialize
6944
0
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6945
0
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6946
0
        window->Active = true;
6947
0
        window->HasCloseButton = (p_open != NULL);
6948
0
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6949
0
        window->IDStack.resize(1);
6950
0
        window->DrawList->_ResetForNewFrame();
6951
0
        window->DC.CurrentTableIdx = -1;
6952
0
        if (flags & ImGuiWindowFlags_DockNodeHost)
6953
0
        {
6954
0
            window->DrawList->ChannelsSplit(2);
6955
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6956
0
        }
6957
6958
        // Restore buffer capacity when woken from a compacted state, to avoid
6959
0
        if (window->MemoryCompacted)
6960
0
            GcAwakeTransientWindowBuffers(window);
6961
6962
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6963
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6964
0
        bool window_title_visible_elsewhere = false;
6965
0
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6966
0
            window_title_visible_elsewhere = true;
6967
0
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6968
0
            window_title_visible_elsewhere = true;
6969
0
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6970
0
        {
6971
0
            size_t buf_len = (size_t)window->NameBufLen;
6972
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6973
0
            window->NameBufLen = (int)buf_len;
6974
0
        }
6975
6976
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6977
6978
        // Update contents size from last frame for auto-fitting (or use explicit size)
6979
0
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6980
6981
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6982
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6983
        // it has a single usage before this code block and may be set below before it is finally checked.
6984
0
        if (window->HiddenFramesCanSkipItems > 0)
6985
0
            window->HiddenFramesCanSkipItems--;
6986
0
        if (window->HiddenFramesCannotSkipItems > 0)
6987
0
            window->HiddenFramesCannotSkipItems--;
6988
0
        if (window->HiddenFramesForRenderOnly > 0)
6989
0
            window->HiddenFramesForRenderOnly--;
6990
6991
        // Hide new windows for one frame until they calculate their size
6992
0
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6993
0
            window->HiddenFramesCannotSkipItems = 1;
6994
6995
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6996
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6997
0
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6998
0
        {
6999
0
            window->HiddenFramesCannotSkipItems = 1;
7000
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7001
0
            {
7002
0
                if (!window_size_x_set_by_api)
7003
0
                    window->Size.x = window->SizeFull.x = 0.f;
7004
0
                if (!window_size_y_set_by_api)
7005
0
                    window->Size.y = window->SizeFull.y = 0.f;
7006
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7007
0
            }
7008
0
        }
7009
7010
        // SELECT VIEWPORT
7011
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7012
7013
0
        WindowSelectViewport(window);
7014
0
        SetCurrentViewport(window, window->Viewport);
7015
0
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7016
0
        SetCurrentWindow(window);
7017
0
        flags = window->Flags;
7018
7019
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7020
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7021
7022
0
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7023
0
            window->WindowBorderSize = style.ChildBorderSize;
7024
0
        else
7025
0
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7026
0
        window->WindowPadding = style.WindowPadding;
7027
0
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7028
0
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7029
7030
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7031
0
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7032
0
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7033
7034
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7035
        // Those flags will be altered further down in the function depending on more conditions.
7036
0
        bool use_current_size_for_scrollbar_x = window_just_created;
7037
0
        bool use_current_size_for_scrollbar_y = window_just_created;
7038
0
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7039
0
            use_current_size_for_scrollbar_x = true;
7040
0
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7041
0
            use_current_size_for_scrollbar_y = true;
7042
7043
        // Collapse window by double-clicking on title bar
7044
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7045
0
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7046
0
        {
7047
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7048
0
            ImRect title_bar_rect = window->TitleBarRect();
7049
0
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7050
0
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_None)
7051
0
                    window->WantCollapseToggle = true;
7052
0
            if (window->WantCollapseToggle)
7053
0
            {
7054
0
                window->Collapsed = !window->Collapsed;
7055
0
                if (!window->Collapsed)
7056
0
                    use_current_size_for_scrollbar_y = true;
7057
0
                MarkIniSettingsDirty(window);
7058
0
            }
7059
0
        }
7060
0
        else
7061
0
        {
7062
0
            window->Collapsed = false;
7063
0
        }
7064
0
        window->WantCollapseToggle = false;
7065
7066
        // SIZE
7067
7068
        // Outer Decoration Sizes
7069
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7070
0
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7071
0
        window->DecoOuterSizeX1 = 0.0f;
7072
0
        window->DecoOuterSizeX2 = 0.0f;
7073
0
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7074
0
        window->DecoOuterSizeY2 = 0.0f;
7075
0
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7076
7077
        // Calculate auto-fit size, handle automatic resize
7078
0
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7079
0
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7080
0
        {
7081
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7082
0
            if (!window_size_x_set_by_api)
7083
0
            {
7084
0
                window->SizeFull.x = size_auto_fit.x;
7085
0
                use_current_size_for_scrollbar_x = true;
7086
0
            }
7087
0
            if (!window_size_y_set_by_api)
7088
0
            {
7089
0
                window->SizeFull.y = size_auto_fit.y;
7090
0
                use_current_size_for_scrollbar_y = true;
7091
0
            }
7092
0
        }
7093
0
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7094
0
        {
7095
            // Auto-fit may only grow window during the first few frames
7096
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7097
0
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7098
0
            {
7099
0
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7100
0
                use_current_size_for_scrollbar_x = true;
7101
0
            }
7102
0
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7103
0
            {
7104
0
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7105
0
                use_current_size_for_scrollbar_y = true;
7106
0
            }
7107
0
            if (!window->Collapsed)
7108
0
                MarkIniSettingsDirty(window);
7109
0
        }
7110
7111
        // Apply minimum/maximum window size constraints and final size
7112
0
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7113
0
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7114
7115
        // POSITION
7116
7117
        // Popup latch its initial position, will position itself when it appears next frame
7118
0
        if (window_just_activated_by_user)
7119
0
        {
7120
0
            window->AutoPosLastDirection = ImGuiDir_None;
7121
0
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7122
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7123
0
        }
7124
7125
        // Position child window
7126
0
        if (flags & ImGuiWindowFlags_ChildWindow)
7127
0
        {
7128
0
            IM_ASSERT(parent_window && parent_window->Active);
7129
0
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7130
0
            parent_window->DC.ChildWindows.push_back(window);
7131
0
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7132
0
                window->Pos = parent_window->DC.CursorPos;
7133
0
        }
7134
7135
0
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7136
0
        if (window_pos_with_pivot)
7137
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7138
0
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7139
0
            window->Pos = FindBestWindowPosForPopup(window);
7140
0
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7141
0
            window->Pos = FindBestWindowPosForPopup(window);
7142
0
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7143
0
            window->Pos = FindBestWindowPosForPopup(window);
7144
7145
        // Late create viewport if we don't fit within our current host viewport.
7146
0
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7147
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7148
0
            {
7149
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7150
                //ImGuiViewport* old_viewport = window->Viewport;
7151
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7152
7153
                // FIXME-DPI
7154
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7155
0
                SetCurrentViewport(window, window->Viewport);
7156
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7157
0
                SetCurrentWindow(window);
7158
0
            }
7159
7160
0
        if (window->ViewportOwned)
7161
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7162
7163
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7164
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7165
0
        ImRect viewport_rect(window->Viewport->GetMainRect());
7166
0
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7167
0
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7168
0
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7169
7170
        // Clamp position/size so window stays visible within its viewport or monitor
7171
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7172
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7173
0
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7174
0
        {
7175
0
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7176
0
            {
7177
0
                ClampWindowPos(window, visibility_rect);
7178
0
            }
7179
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7180
0
            {
7181
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7182
0
                {
7183
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7184
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7185
0
                }
7186
0
                else
7187
0
                {
7188
                    // When not moving ensure visible in its monitor
7189
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7190
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7191
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7192
0
                }
7193
0
                visibility_rect.Expand(-visibility_padding);
7194
0
                ClampWindowPos(window, visibility_rect);
7195
0
            }
7196
0
        }
7197
0
        window->Pos = ImTrunc(window->Pos);
7198
7199
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7200
        // Large values tend to lead to variety of artifacts and are not recommended.
7201
0
        if (window->ViewportOwned || window->DockIsActive)
7202
0
            window->WindowRounding = 0.0f;
7203
0
        else
7204
0
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7205
7206
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7207
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7208
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7209
7210
        // Apply window focus (new and reactivated windows are moved to front)
7211
0
        bool want_focus = false;
7212
0
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7213
0
        {
7214
0
            if (flags & ImGuiWindowFlags_Popup)
7215
0
                want_focus = true;
7216
0
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7217
0
                want_focus = true;
7218
0
        }
7219
7220
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7221
#ifdef IMGUI_ENABLE_TEST_ENGINE
7222
        if (g.TestEngineHookItems)
7223
        {
7224
            IM_ASSERT(window->IDStack.Size == 1);
7225
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7226
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7227
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7228
            window->IDStack.Size = 1;
7229
        }
7230
#endif
7231
7232
        // Decide if we are going to handle borders and resize grips
7233
0
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7234
7235
        // Handle manual resize: Resize Grips, Borders, Gamepad
7236
0
        int border_hovered = -1, border_held = -1;
7237
0
        ImU32 resize_grip_col[4] = {};
7238
0
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7239
0
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7240
0
        if (handle_borders_and_resize_grips && !window->Collapsed)
7241
0
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7242
0
            {
7243
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7244
0
                    use_current_size_for_scrollbar_x = true;
7245
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7246
0
                    use_current_size_for_scrollbar_y = true;
7247
0
            }
7248
0
        window->ResizeBorderHovered = (signed char)border_hovered;
7249
0
        window->ResizeBorderHeld = (signed char)border_held;
7250
7251
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7252
0
        if (window->ViewportOwned)
7253
0
        {
7254
0
            if (!window->Viewport->PlatformRequestMove)
7255
0
                window->Viewport->Pos = window->Pos;
7256
0
            if (!window->Viewport->PlatformRequestResize)
7257
0
                window->Viewport->Size = window->Size;
7258
0
            window->Viewport->UpdateWorkRect();
7259
0
            viewport_rect = window->Viewport->GetMainRect();
7260
0
        }
7261
7262
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7263
0
        window->ViewportPos = window->Viewport->Pos;
7264
7265
        // SCROLLBAR VISIBILITY
7266
7267
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7268
0
        if (!window->Collapsed)
7269
0
        {
7270
            // When reading the current size we need to read it after size constraints have been applied.
7271
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7272
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7273
0
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7274
0
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7275
0
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7276
0
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7277
0
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7278
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7279
0
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7280
0
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7281
0
            if (window->ScrollbarX && !window->ScrollbarY)
7282
0
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7283
0
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7284
7285
            // Amend the partially filled window->DecorationXXX values.
7286
0
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7287
0
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7288
0
        }
7289
7290
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7291
        // Update various regions. Variables they depend on should be set above in this function.
7292
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7293
7294
        // Outer rectangle
7295
        // Not affected by window border size. Used by:
7296
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7297
        // - Begin() initial clipping rect for drawing window background and borders.
7298
        // - Begin() clipping whole child
7299
0
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7300
0
        const ImRect outer_rect = window->Rect();
7301
0
        const ImRect title_bar_rect = window->TitleBarRect();
7302
0
        window->OuterRectClipped = outer_rect;
7303
0
        if (window->DockIsActive)
7304
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7305
0
        window->OuterRectClipped.ClipWith(host_rect);
7306
7307
        // Inner rectangle
7308
        // Not affected by window border size. Used by:
7309
        // - InnerClipRect
7310
        // - ScrollToRectEx()
7311
        // - NavUpdatePageUpPageDown()
7312
        // - Scrollbar()
7313
0
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7314
0
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7315
0
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7316
0
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7317
7318
        // Inner clipping rectangle.
7319
        // Will extend a little bit outside the normal work region.
7320
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7321
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7322
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7323
        // Affected by window/frame border size. Used by:
7324
        // - Begin() initial clip rect
7325
0
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7326
0
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7327
0
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7328
0
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7329
0
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7330
0
        window->InnerClipRect.ClipWithFull(host_rect);
7331
7332
        // Default item width. Make it proportional to window size if window manually resizes
7333
0
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7334
0
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7335
0
        else
7336
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7337
7338
        // SCROLLING
7339
7340
        // Lock down maximum scrolling
7341
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7342
        // for right/bottom aligned items without creating a scrollbar.
7343
0
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7344
0
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7345
7346
        // Apply scrolling
7347
0
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7348
0
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7349
0
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7350
7351
        // DRAWING
7352
7353
        // Setup draw list and outer clipping rectangle
7354
0
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7355
0
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7356
0
        PushClipRect(host_rect.Min, host_rect.Max, false);
7357
7358
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7359
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7360
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7361
0
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7362
0
        if (is_undocked_or_docked_visible)
7363
0
        {
7364
0
            bool render_decorations_in_parent = false;
7365
0
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7366
0
            {
7367
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7368
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7369
0
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7370
0
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7371
0
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7372
0
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7373
0
                    render_decorations_in_parent = true;
7374
0
            }
7375
0
            if (render_decorations_in_parent)
7376
0
                window->DrawList = parent_window->DrawList;
7377
7378
            // Handle title bar, scrollbar, resize grips and resize borders
7379
0
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7380
0
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7381
0
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7382
7383
0
            if (render_decorations_in_parent)
7384
0
                window->DrawList = &window->DrawListInst;
7385
0
        }
7386
7387
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7388
7389
        // Work rectangle.
7390
        // Affected by window padding and border size. Used by:
7391
        // - Columns() for right-most edge
7392
        // - TreeNode(), CollapsingHeader() for right-most edge
7393
        // - BeginTabBar() for right-most edge
7394
0
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7395
0
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7396
0
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7397
0
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7398
0
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7399
0
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7400
0
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7401
0
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7402
0
        window->ParentWorkRect = window->WorkRect;
7403
7404
        // [LEGACY] Content Region
7405
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7406
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7407
        // Used by:
7408
        // - Mouse wheel scrolling + many other things
7409
0
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7410
0
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7411
0
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7412
0
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7413
7414
        // Setup drawing context
7415
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7416
0
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7417
0
        window->DC.GroupOffset.x = 0.0f;
7418
0
        window->DC.ColumnsOffset.x = 0.0f;
7419
7420
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7421
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7422
0
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7423
0
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7424
0
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7425
0
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7426
0
        window->DC.CursorPos = window->DC.CursorStartPos;
7427
0
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7428
0
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7429
0
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7430
0
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7431
0
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7432
0
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7433
7434
0
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7435
0
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7436
0
        window->DC.NavLayersActiveMaskNext = 0x00;
7437
0
        window->DC.NavIsScrollPushableX = true;
7438
0
        window->DC.NavHideHighlightOneFrame = false;
7439
0
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7440
7441
0
        window->DC.MenuBarAppending = false;
7442
0
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7443
0
        window->DC.TreeDepth = 0;
7444
0
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7445
0
        window->DC.ChildWindows.resize(0);
7446
0
        window->DC.StateStorage = &window->StateStorage;
7447
0
        window->DC.CurrentColumns = NULL;
7448
0
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7449
0
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7450
7451
0
        window->DC.ItemWidth = window->ItemWidthDefault;
7452
0
        window->DC.TextWrapPos = -1.0f; // disabled
7453
0
        window->DC.ItemWidthStack.resize(0);
7454
0
        window->DC.TextWrapPosStack.resize(0);
7455
0
        if (flags & ImGuiWindowFlags_Modal)
7456
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7457
7458
0
        if (window->AutoFitFramesX > 0)
7459
0
            window->AutoFitFramesX--;
7460
0
        if (window->AutoFitFramesY > 0)
7461
0
            window->AutoFitFramesY--;
7462
7463
        // Clear SetNextWindowXXX data (can aim to move this higher in the function)
7464
0
        g.NextWindowData.ClearFlags();
7465
7466
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7467
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7468
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7469
        // - Position window behind the modal that is not a begin-parent of this window.
7470
0
        if (want_focus)
7471
0
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7472
0
        if (want_focus && window == g.NavWindow)
7473
0
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7474
7475
        // Close requested by platform window (apply to all windows in this viewport)
7476
0
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7477
0
        {
7478
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7479
0
            *p_open = false;
7480
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7481
0
        }
7482
7483
        // Title bar
7484
0
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7485
0
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7486
7487
        // Clear hit test shape every frame
7488
0
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7489
7490
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7491
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7492
        // Maybe we can support CTRL+C on every element?
7493
        /*
7494
        //if (g.NavWindow == window && g.ActiveId == 0)
7495
        if (g.ActiveId == window->MoveId)
7496
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7497
                LogToClipboard();
7498
        */
7499
7500
0
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7501
0
        {
7502
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7503
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7504
0
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7505
0
                BeginDockableDragDropSource(window);
7506
7507
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7508
0
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7509
0
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7510
0
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7511
0
                        BeginDockableDragDropTarget(window);
7512
0
        }
7513
7514
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7515
        // This is useful to allow creating context menus on title bar only, etc.
7516
0
        SetLastItemDataForWindow(window, title_bar_rect);
7517
7518
        // [DEBUG]
7519
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7520
0
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7521
0
            DebugLocateItemResolveWithLastItem();
7522
0
#endif
7523
7524
        // [Test Engine] Register title bar / tab with MoveId.
7525
#ifdef IMGUI_ENABLE_TEST_ENGINE
7526
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7527
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7528
#endif
7529
0
    }
7530
0
    else
7531
0
    {
7532
        // Append
7533
0
        SetCurrentViewport(window, window->Viewport);
7534
0
        SetCurrentWindow(window);
7535
0
        g.NextWindowData.ClearFlags();
7536
0
        SetLastItemDataForWindow(window, window->TitleBarRect());
7537
0
    }
7538
7539
0
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7540
0
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7541
7542
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7543
0
    window->WriteAccessed = false;
7544
0
    window->BeginCount++;
7545
7546
    // Update visibility
7547
0
    if (first_begin_of_the_frame)
7548
0
    {
7549
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7550
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7551
        // This is analogous to regular windows being hidden from one frame.
7552
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7553
0
        if (window->DockIsActive && !window->DockTabIsVisible)
7554
0
        {
7555
0
            if (window->LastFrameJustFocused == g.FrameCount)
7556
0
                window->HiddenFramesCannotSkipItems = 1;
7557
0
            else
7558
0
                window->HiddenFramesCanSkipItems = 1;
7559
0
        }
7560
7561
0
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7562
0
        {
7563
            // Child window can be out of sight and have "negative" clip windows.
7564
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7565
0
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7566
0
            const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7567
0
            if (!g.LogEnabled && !nav_request)
7568
0
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7569
0
                {
7570
0
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7571
0
                        window->HiddenFramesCannotSkipItems = 1;
7572
0
                    else
7573
0
                        window->HiddenFramesCanSkipItems = 1;
7574
0
                }
7575
7576
            // Hide along with parent or if parent is collapsed
7577
0
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7578
0
                window->HiddenFramesCanSkipItems = 1;
7579
0
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7580
0
                window->HiddenFramesCannotSkipItems = 1;
7581
0
        }
7582
7583
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7584
0
        if (style.Alpha <= 0.0f)
7585
0
            window->HiddenFramesCanSkipItems = 1;
7586
7587
        // Update the Hidden flag
7588
0
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7589
0
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7590
7591
        // Disable inputs for requested number of frames
7592
0
        if (window->DisableInputsFrames > 0)
7593
0
        {
7594
0
            window->DisableInputsFrames--;
7595
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7596
0
        }
7597
7598
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7599
0
        bool skip_items = false;
7600
0
        if (window->Collapsed || !window->Active || hidden_regular)
7601
0
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7602
0
                skip_items = true;
7603
0
        window->SkipItems = skip_items;
7604
7605
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7606
0
        if (window->SkipItems)
7607
0
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7608
7609
        // Sanity check: there are two spots which can set Appearing = true
7610
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7611
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7612
0
        if (window->SkipItems && !window->Appearing)
7613
0
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7614
0
    }
7615
7616
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7617
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7618
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7619
0
    if (!window->IsFallbackWindow)
7620
0
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7621
0
        {
7622
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7623
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7624
0
            return false;
7625
0
        }
7626
0
#endif
7627
7628
0
    return !window->SkipItems;
7629
0
}
7630
7631
static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7632
0
{
7633
0
    ImGuiContext& g = *GImGui;
7634
0
    if (window->DockIsActive)
7635
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7636
0
    else
7637
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7638
0
}
7639
7640
void ImGui::End()
7641
0
{
7642
0
    ImGuiContext& g = *GImGui;
7643
0
    ImGuiWindow* window = g.CurrentWindow;
7644
7645
    // Error checking: verify that user hasn't called End() too many times!
7646
0
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7647
0
    {
7648
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7649
0
        return;
7650
0
    }
7651
0
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7652
7653
    // Error checking: verify that user doesn't directly call End() on a child window.
7654
0
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7655
0
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7656
7657
    // Close anything that is open
7658
0
    if (window->DC.CurrentColumns)
7659
0
        EndColumns();
7660
0
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7661
0
        PopClipRect();
7662
0
    PopFocusScope();
7663
7664
    // Stop logging
7665
0
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7666
0
        LogFinish();
7667
7668
0
    if (window->DC.IsSetPos)
7669
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7670
7671
    // Docking: report contents sizes to parent to allow for auto-resize
7672
0
    if (window->DockNode && window->DockTabIsVisible)
7673
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7674
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7675
7676
    // Pop from window stack
7677
0
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7678
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7679
0
        g.BeginMenuDepth--;
7680
0
    if (window->Flags & ImGuiWindowFlags_Popup)
7681
0
        g.BeginPopupStack.pop_back();
7682
0
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7683
0
    g.CurrentWindowStack.pop_back();
7684
0
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7685
0
    if (g.CurrentWindow)
7686
0
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7687
0
}
7688
7689
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7690
0
{
7691
0
    ImGuiContext& g = *GImGui;
7692
0
    IM_ASSERT(window == window->RootWindow);
7693
7694
0
    const int cur_order = window->FocusOrder;
7695
0
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7696
0
    if (g.WindowsFocusOrder.back() == window)
7697
0
        return;
7698
7699
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7700
0
    for (int n = cur_order; n < new_order; n++)
7701
0
    {
7702
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7703
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7704
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7705
0
    }
7706
0
    g.WindowsFocusOrder[new_order] = window;
7707
0
    window->FocusOrder = (short)new_order;
7708
0
}
7709
7710
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7711
0
{
7712
0
    ImGuiContext& g = *GImGui;
7713
0
    ImGuiWindow* current_front_window = g.Windows.back();
7714
0
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7715
0
        return;
7716
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7717
0
        if (g.Windows[i] == window)
7718
0
        {
7719
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7720
0
            g.Windows[g.Windows.Size - 1] = window;
7721
0
            break;
7722
0
        }
7723
0
}
7724
7725
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7726
0
{
7727
0
    ImGuiContext& g = *GImGui;
7728
0
    if (g.Windows[0] == window)
7729
0
        return;
7730
0
    for (int i = 0; i < g.Windows.Size; i++)
7731
0
        if (g.Windows[i] == window)
7732
0
        {
7733
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7734
0
            g.Windows[0] = window;
7735
0
            break;
7736
0
        }
7737
0
}
7738
7739
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7740
0
{
7741
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7742
0
    ImGuiContext& g = *GImGui;
7743
0
    window = window->RootWindow;
7744
0
    behind_window = behind_window->RootWindow;
7745
0
    int pos_wnd = FindWindowDisplayIndex(window);
7746
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7747
0
    if (pos_wnd < pos_beh)
7748
0
    {
7749
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7750
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7751
0
        g.Windows[pos_beh - 1] = window;
7752
0
    }
7753
0
    else
7754
0
    {
7755
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7756
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7757
0
        g.Windows[pos_beh] = window;
7758
0
    }
7759
0
}
7760
7761
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7762
0
{
7763
0
    ImGuiContext& g = *GImGui;
7764
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7765
0
}
7766
7767
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7768
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7769
0
{
7770
0
    ImGuiContext& g = *GImGui;
7771
7772
    // Modal check?
7773
0
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7774
0
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7775
0
        {
7776
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7777
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7778
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7779
0
            return;
7780
0
        }
7781
7782
    // Find last focused child (if any) and focus it instead.
7783
0
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7784
0
        window = NavRestoreLastChildNavWindow(window);
7785
7786
    // Apply focus
7787
0
    if (g.NavWindow != window)
7788
0
    {
7789
0
        SetNavWindow(window);
7790
0
        if (window && g.NavDisableMouseHover)
7791
0
            g.NavMousePosDirty = true;
7792
0
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7793
0
        g.NavLayer = ImGuiNavLayer_Main;
7794
0
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
7795
0
        g.NavIdIsAlive = false;
7796
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7797
7798
        // Close popups if any
7799
0
        ClosePopupsOverWindow(window, false);
7800
0
    }
7801
7802
    // Move the root window to the top of the pile
7803
0
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7804
0
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7805
0
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7806
0
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7807
0
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7808
7809
    // Steal active widgets. Some of the cases it triggers includes:
7810
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7811
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7812
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7813
0
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7814
0
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7815
0
            ClearActiveID();
7816
7817
    // Passing NULL allow to disable keyboard focus
7818
0
    if (!window)
7819
0
        return;
7820
0
    window->LastFrameJustFocused = g.FrameCount;
7821
7822
    // Select in dock node
7823
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
7824
    //if (dock_node && dock_node->TabBar)
7825
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7826
7827
    // Bring to front
7828
0
    BringWindowToFocusFront(focus_front_window);
7829
0
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7830
0
        BringWindowToDisplayFront(display_front_window);
7831
0
}
7832
7833
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7834
0
{
7835
0
    ImGuiContext& g = *GImGui;
7836
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7837
0
    if (under_this_window != NULL)
7838
0
    {
7839
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7840
0
        int offset = -1;
7841
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7842
0
        {
7843
0
            under_this_window = under_this_window->ParentWindow;
7844
0
            offset = 0;
7845
0
        }
7846
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7847
0
    }
7848
0
    for (int i = start_idx; i >= 0; i--)
7849
0
    {
7850
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7851
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7852
0
        if (window == ignore_window || !window->WasActive)
7853
0
            continue;
7854
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7855
0
            continue;
7856
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7857
0
        {
7858
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7859
            // This is failing (lagging by one frame) for docked windows.
7860
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7861
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7862
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7863
0
            FocusWindow(window, flags);
7864
0
            return;
7865
0
        }
7866
0
    }
7867
0
    FocusWindow(NULL, flags);
7868
0
}
7869
7870
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7871
void ImGui::SetCurrentFont(ImFont* font)
7872
0
{
7873
0
    ImGuiContext& g = *GImGui;
7874
0
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7875
0
    IM_ASSERT(font->Scale > 0.0f);
7876
0
    g.Font = font;
7877
0
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7878
0
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7879
7880
0
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7881
0
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7882
0
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7883
0
    g.DrawListSharedData.Font = g.Font;
7884
0
    g.DrawListSharedData.FontSize = g.FontSize;
7885
0
}
7886
7887
void ImGui::PushFont(ImFont* font)
7888
0
{
7889
0
    ImGuiContext& g = *GImGui;
7890
0
    if (!font)
7891
0
        font = GetDefaultFont();
7892
0
    SetCurrentFont(font);
7893
0
    g.FontStack.push_back(font);
7894
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7895
0
}
7896
7897
void  ImGui::PopFont()
7898
0
{
7899
0
    ImGuiContext& g = *GImGui;
7900
0
    g.CurrentWindow->DrawList->PopTextureID();
7901
0
    g.FontStack.pop_back();
7902
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7903
0
}
7904
7905
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7906
0
{
7907
0
    ImGuiContext& g = *GImGui;
7908
0
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7909
0
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7910
0
    if (enabled)
7911
0
        item_flags |= option;
7912
0
    else
7913
0
        item_flags &= ~option;
7914
0
    g.CurrentItemFlags = item_flags;
7915
0
    g.ItemFlagsStack.push_back(item_flags);
7916
0
}
7917
7918
void ImGui::PopItemFlag()
7919
0
{
7920
0
    ImGuiContext& g = *GImGui;
7921
0
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7922
0
    g.ItemFlagsStack.pop_back();
7923
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7924
0
}
7925
7926
// BeginDisabled()/EndDisabled()
7927
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7928
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7929
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7930
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7931
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7932
void ImGui::BeginDisabled(bool disabled)
7933
0
{
7934
0
    ImGuiContext& g = *GImGui;
7935
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7936
0
    if (!was_disabled && disabled)
7937
0
    {
7938
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7939
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7940
0
    }
7941
0
    if (was_disabled || disabled)
7942
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7943
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7944
0
    g.DisabledStackSize++;
7945
0
}
7946
7947
void ImGui::EndDisabled()
7948
0
{
7949
0
    ImGuiContext& g = *GImGui;
7950
0
    IM_ASSERT(g.DisabledStackSize > 0);
7951
0
    g.DisabledStackSize--;
7952
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7953
    //PopItemFlag();
7954
0
    g.ItemFlagsStack.pop_back();
7955
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7956
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7957
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7958
0
}
7959
7960
void ImGui::PushTabStop(bool tab_stop)
7961
0
{
7962
0
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7963
0
}
7964
7965
void ImGui::PopTabStop()
7966
0
{
7967
0
    PopItemFlag();
7968
0
}
7969
7970
void ImGui::PushButtonRepeat(bool repeat)
7971
0
{
7972
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7973
0
}
7974
7975
void ImGui::PopButtonRepeat()
7976
0
{
7977
0
    PopItemFlag();
7978
0
}
7979
7980
void ImGui::PushTextWrapPos(float wrap_pos_x)
7981
0
{
7982
0
    ImGuiWindow* window = GetCurrentWindow();
7983
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7984
0
    window->DC.TextWrapPos = wrap_pos_x;
7985
0
}
7986
7987
void ImGui::PopTextWrapPos()
7988
0
{
7989
0
    ImGuiWindow* window = GetCurrentWindow();
7990
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7991
0
    window->DC.TextWrapPosStack.pop_back();
7992
0
}
7993
7994
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7995
0
{
7996
0
    ImGuiWindow* last_window = NULL;
7997
0
    while (last_window != window)
7998
0
    {
7999
0
        last_window = window;
8000
0
        window = window->RootWindow;
8001
0
        if (popup_hierarchy)
8002
0
            window = window->RootWindowPopupTree;
8003
0
    if (dock_hierarchy)
8004
0
      window = window->RootWindowDockTree;
8005
0
  }
8006
0
    return window;
8007
0
}
8008
8009
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8010
0
{
8011
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8012
0
    if (window_root == potential_parent)
8013
0
        return true;
8014
0
    while (window != NULL)
8015
0
    {
8016
0
        if (window == potential_parent)
8017
0
            return true;
8018
0
        if (window == window_root) // end of chain
8019
0
            return false;
8020
0
        window = window->ParentWindow;
8021
0
    }
8022
0
    return false;
8023
0
}
8024
8025
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8026
0
{
8027
0
    if (window->RootWindow == potential_parent)
8028
0
        return true;
8029
0
    while (window != NULL)
8030
0
    {
8031
0
        if (window == potential_parent)
8032
0
            return true;
8033
0
        window = window->ParentWindowInBeginStack;
8034
0
    }
8035
0
    return false;
8036
0
}
8037
8038
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8039
0
{
8040
0
    ImGuiContext& g = *GImGui;
8041
8042
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8043
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8044
0
    if (display_layer_delta != 0)
8045
0
        return display_layer_delta > 0;
8046
8047
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8048
0
    {
8049
0
        ImGuiWindow* candidate_window = g.Windows[i];
8050
0
        if (candidate_window == potential_above)
8051
0
            return true;
8052
0
        if (candidate_window == potential_below)
8053
0
            return false;
8054
0
    }
8055
0
    return false;
8056
0
}
8057
8058
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8059
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8060
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8061
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8062
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8063
0
{
8064
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8065
8066
0
    ImGuiContext& g = *GImGui;
8067
0
    ImGuiWindow* ref_window = g.HoveredWindow;
8068
0
    ImGuiWindow* cur_window = g.CurrentWindow;
8069
0
    if (ref_window == NULL)
8070
0
        return false;
8071
8072
0
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8073
0
    {
8074
0
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8075
0
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8076
0
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8077
0
        if (flags & ImGuiHoveredFlags_RootWindow)
8078
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8079
8080
0
        bool result;
8081
0
        if (flags & ImGuiHoveredFlags_ChildWindows)
8082
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8083
0
        else
8084
0
            result = (ref_window == cur_window);
8085
0
        if (!result)
8086
0
            return false;
8087
0
    }
8088
8089
0
    if (!IsWindowContentHoverable(ref_window, flags))
8090
0
        return false;
8091
0
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8092
0
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8093
0
            return false;
8094
8095
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8096
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8097
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8098
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8099
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8100
0
    if (flags & ImGuiHoveredFlags_ForTooltip)
8101
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8102
0
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8103
0
        return false;
8104
8105
0
    return true;
8106
0
}
8107
8108
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8109
0
{
8110
0
    ImGuiContext& g = *GImGui;
8111
0
    ImGuiWindow* ref_window = g.NavWindow;
8112
0
    ImGuiWindow* cur_window = g.CurrentWindow;
8113
8114
0
    if (ref_window == NULL)
8115
0
        return false;
8116
0
    if (flags & ImGuiFocusedFlags_AnyWindow)
8117
0
        return true;
8118
8119
0
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8120
0
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8121
0
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8122
0
    if (flags & ImGuiHoveredFlags_RootWindow)
8123
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8124
8125
0
    if (flags & ImGuiHoveredFlags_ChildWindows)
8126
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8127
0
    else
8128
0
        return (ref_window == cur_window);
8129
0
}
8130
8131
ImGuiID ImGui::GetWindowDockID()
8132
0
{
8133
0
    ImGuiContext& g = *GImGui;
8134
0
    return g.CurrentWindow->DockId;
8135
0
}
8136
8137
bool ImGui::IsWindowDocked()
8138
0
{
8139
0
    ImGuiContext& g = *GImGui;
8140
0
    return g.CurrentWindow->DockIsActive;
8141
0
}
8142
8143
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8144
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8145
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8146
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8147
0
{
8148
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8149
0
}
8150
8151
float ImGui::GetWindowWidth()
8152
0
{
8153
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8154
0
    return window->Size.x;
8155
0
}
8156
8157
float ImGui::GetWindowHeight()
8158
0
{
8159
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8160
0
    return window->Size.y;
8161
0
}
8162
8163
ImVec2 ImGui::GetWindowPos()
8164
0
{
8165
0
    ImGuiContext& g = *GImGui;
8166
0
    ImGuiWindow* window = g.CurrentWindow;
8167
0
    return window->Pos;
8168
0
}
8169
8170
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8171
0
{
8172
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8173
0
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8174
0
        return;
8175
8176
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8177
0
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8178
0
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8179
8180
    // Set
8181
0
    const ImVec2 old_pos = window->Pos;
8182
0
    window->Pos = ImTrunc(pos);
8183
0
    ImVec2 offset = window->Pos - old_pos;
8184
0
    if (offset.x == 0.0f && offset.y == 0.0f)
8185
0
        return;
8186
0
    MarkIniSettingsDirty(window);
8187
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8188
0
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8189
0
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8190
0
    window->DC.IdealMaxPos += offset;
8191
0
    window->DC.CursorStartPos += offset;
8192
0
}
8193
8194
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8195
0
{
8196
0
    ImGuiWindow* window = GetCurrentWindowRead();
8197
0
    SetWindowPos(window, pos, cond);
8198
0
}
8199
8200
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8201
0
{
8202
0
    if (ImGuiWindow* window = FindWindowByName(name))
8203
0
        SetWindowPos(window, pos, cond);
8204
0
}
8205
8206
ImVec2 ImGui::GetWindowSize()
8207
0
{
8208
0
    ImGuiWindow* window = GetCurrentWindowRead();
8209
0
    return window->Size;
8210
0
}
8211
8212
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8213
0
{
8214
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8215
0
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8216
0
        return;
8217
8218
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8219
0
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8220
8221
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8222
0
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8223
0
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8224
0
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8225
0
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8226
8227
    // Set
8228
0
    ImVec2 old_size = window->SizeFull;
8229
0
    if (size.x <= 0.0f)
8230
0
        window->AutoFitOnlyGrows = false;
8231
0
    else
8232
0
        window->SizeFull.x = IM_TRUNC(size.x);
8233
0
    if (size.y <= 0.0f)
8234
0
        window->AutoFitOnlyGrows = false;
8235
0
    else
8236
0
        window->SizeFull.y = IM_TRUNC(size.y);
8237
0
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8238
0
        MarkIniSettingsDirty(window);
8239
0
}
8240
8241
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8242
0
{
8243
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8244
0
}
8245
8246
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8247
0
{
8248
0
    if (ImGuiWindow* window = FindWindowByName(name))
8249
0
        SetWindowSize(window, size, cond);
8250
0
}
8251
8252
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8253
0
{
8254
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8255
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8256
0
        return;
8257
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8258
8259
    // Set
8260
0
    window->Collapsed = collapsed;
8261
0
}
8262
8263
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8264
0
{
8265
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8266
0
    window->HitTestHoleSize = ImVec2ih(size);
8267
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8268
0
}
8269
8270
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8271
0
{
8272
0
    window->Hidden = window->SkipItems = true;
8273
0
    window->HiddenFramesCanSkipItems = 1;
8274
0
}
8275
8276
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8277
0
{
8278
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8279
0
}
8280
8281
bool ImGui::IsWindowCollapsed()
8282
0
{
8283
0
    ImGuiWindow* window = GetCurrentWindowRead();
8284
0
    return window->Collapsed;
8285
0
}
8286
8287
bool ImGui::IsWindowAppearing()
8288
0
{
8289
0
    ImGuiWindow* window = GetCurrentWindowRead();
8290
0
    return window->Appearing;
8291
0
}
8292
8293
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8294
0
{
8295
0
    if (ImGuiWindow* window = FindWindowByName(name))
8296
0
        SetWindowCollapsed(window, collapsed, cond);
8297
0
}
8298
8299
void ImGui::SetWindowFocus()
8300
0
{
8301
0
    FocusWindow(GImGui->CurrentWindow);
8302
0
}
8303
8304
void ImGui::SetWindowFocus(const char* name)
8305
0
{
8306
0
    if (name)
8307
0
    {
8308
0
        if (ImGuiWindow* window = FindWindowByName(name))
8309
0
            FocusWindow(window);
8310
0
    }
8311
0
    else
8312
0
    {
8313
0
        FocusWindow(NULL);
8314
0
    }
8315
0
}
8316
8317
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8318
0
{
8319
0
    ImGuiContext& g = *GImGui;
8320
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8321
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8322
0
    g.NextWindowData.PosVal = pos;
8323
0
    g.NextWindowData.PosPivotVal = pivot;
8324
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8325
0
    g.NextWindowData.PosUndock = true;
8326
0
}
8327
8328
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8329
0
{
8330
0
    ImGuiContext& g = *GImGui;
8331
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8332
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8333
0
    g.NextWindowData.SizeVal = size;
8334
0
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8335
0
}
8336
8337
// For each axis:
8338
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8339
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8340
// - See "Demo->Examples->Constrained-resizing window" for examples.
8341
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8342
0
{
8343
0
    ImGuiContext& g = *GImGui;
8344
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8345
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8346
0
    g.NextWindowData.SizeCallback = custom_callback;
8347
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8348
0
}
8349
8350
// Content size = inner scrollable rectangle, padded with WindowPadding.
8351
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8352
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8353
0
{
8354
0
    ImGuiContext& g = *GImGui;
8355
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8356
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8357
0
}
8358
8359
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8360
0
{
8361
0
    ImGuiContext& g = *GImGui;
8362
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8363
0
    g.NextWindowData.ScrollVal = scroll;
8364
0
}
8365
8366
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8367
0
{
8368
0
    ImGuiContext& g = *GImGui;
8369
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8370
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8371
0
    g.NextWindowData.CollapsedVal = collapsed;
8372
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8373
0
}
8374
8375
void ImGui::SetNextWindowFocus()
8376
0
{
8377
0
    ImGuiContext& g = *GImGui;
8378
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8379
0
}
8380
8381
void ImGui::SetNextWindowBgAlpha(float alpha)
8382
0
{
8383
0
    ImGuiContext& g = *GImGui;
8384
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8385
0
    g.NextWindowData.BgAlphaVal = alpha;
8386
0
}
8387
8388
void ImGui::SetNextWindowViewport(ImGuiID id)
8389
0
{
8390
0
    ImGuiContext& g = *GImGui;
8391
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8392
0
    g.NextWindowData.ViewportId = id;
8393
0
}
8394
8395
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8396
0
{
8397
0
    ImGuiContext& g = *GImGui;
8398
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8399
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8400
0
    g.NextWindowData.DockId = id;
8401
0
}
8402
8403
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8404
0
{
8405
0
    ImGuiContext& g = *GImGui;
8406
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8407
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8408
0
    g.NextWindowData.WindowClass = *window_class;
8409
0
}
8410
8411
ImDrawList* ImGui::GetWindowDrawList()
8412
0
{
8413
0
    ImGuiWindow* window = GetCurrentWindow();
8414
0
    return window->DrawList;
8415
0
}
8416
8417
float ImGui::GetWindowDpiScale()
8418
0
{
8419
0
    ImGuiContext& g = *GImGui;
8420
0
    return g.CurrentDpiScale;
8421
0
}
8422
8423
ImGuiViewport* ImGui::GetWindowViewport()
8424
0
{
8425
0
    ImGuiContext& g = *GImGui;
8426
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8427
0
    return g.CurrentViewport;
8428
0
}
8429
8430
ImFont* ImGui::GetFont()
8431
0
{
8432
0
    return GImGui->Font;
8433
0
}
8434
8435
float ImGui::GetFontSize()
8436
0
{
8437
0
    return GImGui->FontSize;
8438
0
}
8439
8440
ImVec2 ImGui::GetFontTexUvWhitePixel()
8441
0
{
8442
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8443
0
}
8444
8445
void ImGui::SetWindowFontScale(float scale)
8446
0
{
8447
0
    IM_ASSERT(scale > 0.0f);
8448
0
    ImGuiContext& g = *GImGui;
8449
0
    ImGuiWindow* window = GetCurrentWindow();
8450
0
    window->FontWindowScale = scale;
8451
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8452
0
}
8453
8454
void ImGui::PushFocusScope(ImGuiID id)
8455
0
{
8456
0
    ImGuiContext& g = *GImGui;
8457
0
    ImGuiFocusScopeData data;
8458
0
    data.ID = id;
8459
0
    data.WindowID = g.CurrentWindow->ID;
8460
0
    g.FocusScopeStack.push_back(data);
8461
0
    g.CurrentFocusScopeId = id;
8462
0
}
8463
8464
void ImGui::PopFocusScope()
8465
0
{
8466
0
    ImGuiContext& g = *GImGui;
8467
0
    if (g.FocusScopeStack.Size == 0)
8468
0
    {
8469
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8470
0
        return;
8471
0
    }
8472
0
    g.FocusScopeStack.pop_back();
8473
0
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8474
0
}
8475
8476
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8477
0
{
8478
0
    ImGuiContext& g = *GImGui;
8479
0
    g.NavFocusScopeId = focus_scope_id;
8480
0
    g.NavFocusRoute.resize(0); // Invalidate
8481
0
    if (focus_scope_id == 0)
8482
0
        return;
8483
0
    IM_ASSERT(g.NavWindow != NULL);
8484
8485
    // Store current path (in reverse order)
8486
0
    if (focus_scope_id == g.CurrentFocusScopeId)
8487
0
    {
8488
        // Top of focus stack contains local focus scopes inside current window
8489
0
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8490
0
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8491
0
    }
8492
0
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8493
0
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8494
0
    else
8495
0
        return;
8496
8497
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8498
0
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8499
0
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8500
0
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8501
0
}
8502
8503
// Focus = move navigation cursor, set scrolling, set focus window.
8504
void ImGui::FocusItem()
8505
0
{
8506
0
    ImGuiContext& g = *GImGui;
8507
0
    ImGuiWindow* window = g.CurrentWindow;
8508
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8509
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8510
0
    {
8511
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8512
0
        return;
8513
0
    }
8514
8515
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8516
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8517
0
    SetNavWindow(window);
8518
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8519
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8520
0
}
8521
8522
void ImGui::ActivateItemByID(ImGuiID id)
8523
0
{
8524
0
    ImGuiContext& g = *GImGui;
8525
0
    g.NavNextActivateId = id;
8526
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8527
0
}
8528
8529
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8530
// But ActivateItem() should function without altering scroll/focus?
8531
void ImGui::SetKeyboardFocusHere(int offset)
8532
0
{
8533
0
    ImGuiContext& g = *GImGui;
8534
0
    ImGuiWindow* window = g.CurrentWindow;
8535
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8536
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8537
8538
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8539
    // When we refactor this function into ActivateItem() we may want to make this an option.
8540
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8541
    // is also automatically dropped in the event g.ActiveId is stolen.
8542
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8543
0
    {
8544
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8545
0
        return;
8546
0
    }
8547
8548
0
    SetNavWindow(window);
8549
8550
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8551
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8552
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8553
0
    if (offset == -1)
8554
0
    {
8555
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8556
0
    }
8557
0
    else
8558
0
    {
8559
0
        g.NavTabbingDir = 1;
8560
0
        g.NavTabbingCounter = offset + 1;
8561
0
    }
8562
0
}
8563
8564
void ImGui::SetItemDefaultFocus()
8565
0
{
8566
0
    ImGuiContext& g = *GImGui;
8567
0
    ImGuiWindow* window = g.CurrentWindow;
8568
0
    if (!window->Appearing)
8569
0
        return;
8570
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8571
0
        return;
8572
8573
0
    g.NavInitRequest = false;
8574
0
    NavApplyItemToResult(&g.NavInitResult);
8575
0
    NavUpdateAnyRequestFlag();
8576
8577
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8578
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8579
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8580
0
}
8581
8582
void ImGui::SetStateStorage(ImGuiStorage* tree)
8583
0
{
8584
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8585
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8586
0
}
8587
8588
ImGuiStorage* ImGui::GetStateStorage()
8589
0
{
8590
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8591
0
    return window->DC.StateStorage;
8592
0
}
8593
8594
bool ImGui::IsRectVisible(const ImVec2& size)
8595
0
{
8596
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8597
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8598
0
}
8599
8600
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8601
0
{
8602
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8603
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8604
0
}
8605
8606
//-----------------------------------------------------------------------------
8607
// [SECTION] ID STACK
8608
//-----------------------------------------------------------------------------
8609
8610
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8611
// it should ideally be flattened at some point but it's been used a lots by widgets.
8612
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8613
0
{
8614
0
    ImGuiID seed = IDStack.back();
8615
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8616
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8617
0
    ImGuiContext& g = *Ctx;
8618
0
    if (g.DebugHookIdInfo == id)
8619
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8620
0
#endif
8621
0
    return id;
8622
0
}
8623
8624
ImGuiID ImGuiWindow::GetID(const void* ptr)
8625
0
{
8626
0
    ImGuiID seed = IDStack.back();
8627
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8628
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8629
0
    ImGuiContext& g = *Ctx;
8630
0
    if (g.DebugHookIdInfo == id)
8631
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8632
0
#endif
8633
0
    return id;
8634
0
}
8635
8636
ImGuiID ImGuiWindow::GetID(int n)
8637
0
{
8638
0
    ImGuiID seed = IDStack.back();
8639
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8640
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8641
0
    ImGuiContext& g = *Ctx;
8642
0
    if (g.DebugHookIdInfo == id)
8643
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8644
0
#endif
8645
0
    return id;
8646
0
}
8647
8648
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8649
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8650
0
{
8651
0
    ImGuiID seed = IDStack.back();
8652
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8653
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8654
0
    return id;
8655
0
}
8656
8657
void ImGui::PushID(const char* str_id)
8658
0
{
8659
0
    ImGuiContext& g = *GImGui;
8660
0
    ImGuiWindow* window = g.CurrentWindow;
8661
0
    ImGuiID id = window->GetID(str_id);
8662
0
    window->IDStack.push_back(id);
8663
0
}
8664
8665
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8666
0
{
8667
0
    ImGuiContext& g = *GImGui;
8668
0
    ImGuiWindow* window = g.CurrentWindow;
8669
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8670
0
    window->IDStack.push_back(id);
8671
0
}
8672
8673
void ImGui::PushID(const void* ptr_id)
8674
0
{
8675
0
    ImGuiContext& g = *GImGui;
8676
0
    ImGuiWindow* window = g.CurrentWindow;
8677
0
    ImGuiID id = window->GetID(ptr_id);
8678
0
    window->IDStack.push_back(id);
8679
0
}
8680
8681
void ImGui::PushID(int int_id)
8682
0
{
8683
0
    ImGuiContext& g = *GImGui;
8684
0
    ImGuiWindow* window = g.CurrentWindow;
8685
0
    ImGuiID id = window->GetID(int_id);
8686
0
    window->IDStack.push_back(id);
8687
0
}
8688
8689
// Push a given id value ignoring the ID stack as a seed.
8690
void ImGui::PushOverrideID(ImGuiID id)
8691
0
{
8692
0
    ImGuiContext& g = *GImGui;
8693
0
    ImGuiWindow* window = g.CurrentWindow;
8694
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8695
0
    if (g.DebugHookIdInfo == id)
8696
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8697
0
#endif
8698
0
    window->IDStack.push_back(id);
8699
0
}
8700
8701
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8702
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8703
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8704
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8705
0
{
8706
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8707
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8708
0
    ImGuiContext& g = *GImGui;
8709
0
    if (g.DebugHookIdInfo == id)
8710
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8711
0
#endif
8712
0
    return id;
8713
0
}
8714
8715
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8716
0
{
8717
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8718
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8719
0
    ImGuiContext& g = *GImGui;
8720
0
    if (g.DebugHookIdInfo == id)
8721
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8722
0
#endif
8723
0
    return id;
8724
0
}
8725
8726
void ImGui::PopID()
8727
0
{
8728
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8729
0
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8730
0
    window->IDStack.pop_back();
8731
0
}
8732
8733
ImGuiID ImGui::GetID(const char* str_id)
8734
0
{
8735
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8736
0
    return window->GetID(str_id);
8737
0
}
8738
8739
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8740
0
{
8741
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8742
0
    return window->GetID(str_id_begin, str_id_end);
8743
0
}
8744
8745
ImGuiID ImGui::GetID(const void* ptr_id)
8746
0
{
8747
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8748
0
    return window->GetID(ptr_id);
8749
0
}
8750
8751
//-----------------------------------------------------------------------------
8752
// [SECTION] INPUTS
8753
//-----------------------------------------------------------------------------
8754
// - GetKeyData() [Internal]
8755
// - GetKeyIndex() [Internal]
8756
// - GetKeyName()
8757
// - GetKeyChordName() [Internal]
8758
// - CalcTypematicRepeatAmount() [Internal]
8759
// - GetTypematicRepeatRate() [Internal]
8760
// - GetKeyPressedAmount() [Internal]
8761
// - GetKeyMagnitude2d() [Internal]
8762
//-----------------------------------------------------------------------------
8763
// - UpdateKeyRoutingTable() [Internal]
8764
// - GetRoutingIdFromOwnerId() [Internal]
8765
// - GetShortcutRoutingData() [Internal]
8766
// - CalcRoutingScore() [Internal]
8767
// - SetShortcutRouting() [Internal]
8768
// - TestShortcutRouting() [Internal]
8769
//-----------------------------------------------------------------------------
8770
// - IsKeyDown()
8771
// - IsKeyPressed()
8772
// - IsKeyReleased()
8773
//-----------------------------------------------------------------------------
8774
// - IsMouseDown()
8775
// - IsMouseClicked()
8776
// - IsMouseReleased()
8777
// - IsMouseDoubleClicked()
8778
// - GetMouseClickedCount()
8779
// - IsMouseHoveringRect() [Internal]
8780
// - IsMouseDragPastThreshold() [Internal]
8781
// - IsMouseDragging()
8782
// - GetMousePos()
8783
// - SetMousePos() [Internal]
8784
// - GetMousePosOnOpeningCurrentPopup()
8785
// - IsMousePosValid()
8786
// - IsAnyMouseDown()
8787
// - GetMouseDragDelta()
8788
// - ResetMouseDragDelta()
8789
// - GetMouseCursor()
8790
// - SetMouseCursor()
8791
//-----------------------------------------------------------------------------
8792
// - UpdateAliasKey()
8793
// - GetMergedModsFromKeys()
8794
// - UpdateKeyboardInputs()
8795
// - UpdateMouseInputs()
8796
//-----------------------------------------------------------------------------
8797
// - LockWheelingWindow [Internal]
8798
// - FindBestWheelingWindow [Internal]
8799
// - UpdateMouseWheel() [Internal]
8800
//-----------------------------------------------------------------------------
8801
// - SetNextFrameWantCaptureKeyboard()
8802
// - SetNextFrameWantCaptureMouse()
8803
//-----------------------------------------------------------------------------
8804
// - GetInputSourceName() [Internal]
8805
// - DebugPrintInputEvent() [Internal]
8806
// - UpdateInputEvents() [Internal]
8807
//-----------------------------------------------------------------------------
8808
// - GetKeyOwner() [Internal]
8809
// - TestKeyOwner() [Internal]
8810
// - SetKeyOwner() [Internal]
8811
// - SetItemKeyOwner() [Internal]
8812
// - Shortcut() [Internal]
8813
//-----------------------------------------------------------------------------
8814
8815
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiContext* ctx, ImGuiKeyChord key_chord)
8816
0
{
8817
    // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
8818
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8819
0
    if (IsModKey(key))
8820
0
    {
8821
0
        if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
8822
0
            key_chord |= ImGuiMod_Ctrl;
8823
0
        if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
8824
0
            key_chord |= ImGuiMod_Shift;
8825
0
        if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
8826
0
            key_chord |= ImGuiMod_Alt;
8827
0
        if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
8828
0
            key_chord |= ImGuiMod_Super;
8829
0
    }
8830
0
    if (key_chord & ImGuiMod_Shortcut)
8831
0
        return (key_chord & ~ImGuiMod_Shortcut) | (ctx->IO.ConfigMacOSXBehaviors ? ImGuiMod_Super : ImGuiMod_Ctrl);
8832
0
    return key_chord;
8833
0
}
8834
8835
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8836
0
{
8837
0
    ImGuiContext& g = *ctx;
8838
8839
    // Special storage location for mods
8840
0
    if (key & ImGuiMod_Mask_)
8841
0
        key = ConvertSingleModFlagToKey(ctx, key);
8842
8843
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8844
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8845
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8846
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8847
#else
8848
0
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8849
0
#endif
8850
0
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8851
0
}
8852
8853
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8854
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8855
{
8856
    ImGuiContext& g = *GImGui;
8857
    IM_ASSERT(IsNamedKey(key));
8858
    const ImGuiKeyData* key_data = GetKeyData(key);
8859
    return (ImGuiKey)(key_data - g.IO.KeysData);
8860
}
8861
#endif
8862
8863
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8864
static const char* const GKeyNames[] =
8865
{
8866
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8867
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8868
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8869
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8870
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8871
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8872
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8873
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8874
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8875
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8876
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8877
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8878
    "AppBack", "AppForward",
8879
    "GamepadStart", "GamepadBack",
8880
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8881
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8882
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8883
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8884
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8885
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8886
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8887
};
8888
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8889
8890
const char* ImGui::GetKeyName(ImGuiKey key)
8891
0
{
8892
0
    ImGuiContext& g = *GImGui;
8893
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8894
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8895
#else
8896
    if (IsLegacyKey(key))
8897
    {
8898
        if (g.IO.KeyMap[key] == -1)
8899
            return "N/A";
8900
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8901
        key = (ImGuiKey)g.IO.KeyMap[key];
8902
    }
8903
#endif
8904
0
    if (key == ImGuiKey_None)
8905
0
        return "None";
8906
0
    if (key & ImGuiMod_Mask_)
8907
0
        key = ConvertSingleModFlagToKey(&g, key);
8908
0
    if (!IsNamedKey(key))
8909
0
        return "Unknown";
8910
8911
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8912
0
}
8913
8914
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8915
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
8916
0
{
8917
0
    ImGuiContext& g = *GImGui;
8918
0
    key_chord = FixupKeyChord(&g, key_chord);
8919
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
8920
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8921
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8922
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8923
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8924
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8925
0
    return g.TempKeychordName;
8926
0
}
8927
8928
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8929
// t1 = current time (e.g.: g.Time)
8930
// An event is triggered at:
8931
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8932
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8933
0
{
8934
0
    if (t1 == 0.0f)
8935
0
        return 1;
8936
0
    if (t0 >= t1)
8937
0
        return 0;
8938
0
    if (repeat_rate <= 0.0f)
8939
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8940
0
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8941
0
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8942
0
    const int count = count_t1 - count_t0;
8943
0
    return count;
8944
0
}
8945
8946
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8947
0
{
8948
0
    ImGuiContext& g = *GImGui;
8949
0
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8950
0
    {
8951
0
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8952
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8953
0
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8954
0
    }
8955
0
}
8956
8957
// Return value representing the number of presses in the last time period, for the given repeat rate
8958
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8959
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8960
0
{
8961
0
    ImGuiContext& g = *GImGui;
8962
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8963
0
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8964
0
        return 0;
8965
0
    const float t = key_data->DownDuration;
8966
0
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8967
0
}
8968
8969
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8970
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8971
0
{
8972
0
    return ImVec2(
8973
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8974
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8975
0
}
8976
8977
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8978
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8979
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8980
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8981
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8982
0
{
8983
0
    ImGuiContext& g = *GImGui;
8984
0
    rt->EntriesNext.resize(0);
8985
0
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8986
0
    {
8987
0
        const int new_routing_start_idx = rt->EntriesNext.Size;
8988
0
        ImGuiKeyRoutingData* routing_entry;
8989
0
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8990
0
        {
8991
0
            routing_entry = &rt->Entries[old_routing_idx];
8992
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
8993
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8994
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8995
0
            routing_entry->RoutingNextScore = 255;
8996
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8997
0
                continue;
8998
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8999
9000
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9001
            // This is the result of previous frame's SetShortcutRouting() call.
9002
0
            if (routing_entry->Mods == g.IO.KeyMods)
9003
0
            {
9004
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9005
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
9006
0
                {
9007
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
9008
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9009
0
                }
9010
0
            }
9011
0
        }
9012
9013
        // Rewrite linked-list
9014
0
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9015
0
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9016
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9017
0
    }
9018
0
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9019
0
}
9020
9021
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9022
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9023
0
{
9024
0
    ImGuiContext& g = *GImGui;
9025
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9026
0
}
9027
9028
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9029
0
{
9030
    // Majority of shortcuts will be Key + any number of Mods
9031
    // We accept _Single_ mod with ImGuiKey_None.
9032
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9033
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9034
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9035
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9036
0
    ImGuiContext& g = *GImGui;
9037
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9038
0
    ImGuiKeyRoutingData* routing_data;
9039
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9040
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9041
0
    if (key == ImGuiKey_None)
9042
0
        key = ConvertSingleModFlagToKey(&g, mods);
9043
0
    IM_ASSERT(IsNamedKey(key) && (key_chord & ImGuiMod_Shortcut) == 0); // Please call ConvertShortcutMod() in calling function.
9044
9045
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9046
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9047
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9048
0
    {
9049
0
        routing_data = &rt->Entries[idx];
9050
0
        if (routing_data->Mods == mods)
9051
0
            return routing_data;
9052
0
    }
9053
9054
    // Add to linked-list
9055
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9056
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9057
0
    routing_data = &rt->Entries[routing_data_idx];
9058
0
    routing_data->Mods = (ImU16)mods;
9059
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9060
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9061
0
    return routing_data;
9062
0
}
9063
9064
// Current score encoding (lower is highest priority):
9065
//  -   0: ImGuiInputFlags_RouteGlobalHigh
9066
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
9067
//  -   2: ImGuiInputFlags_RouteGlobal
9068
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9069
//  - 254: ImGuiInputFlags_RouteGlobalLow
9070
//  - 255: never route
9071
// 'flags' should include an explicit routing policy
9072
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9073
0
{
9074
0
    if (flags & ImGuiInputFlags_RouteFocused)
9075
0
    {
9076
0
        ImGuiContext& g = *GImGui;
9077
9078
        // ActiveID gets top priority
9079
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9080
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9081
0
            return 1;
9082
9083
        // Score based on distance to focused window (lower is better)
9084
        // Assuming both windows are submitting a routing request,
9085
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9086
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9087
        // Assuming only WindowA is submitting a routing request,
9088
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9089
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9090
0
        if (focus_scope_id == 0)
9091
0
            return 255;
9092
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9093
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9094
0
                return 3 + index_in_focus_path;
9095
9096
0
        return 255;
9097
0
    }
9098
9099
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
9100
0
    if (flags & ImGuiInputFlags_RouteGlobal)
9101
0
        return 2;
9102
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
9103
0
        return 254;
9104
0
    return 0;
9105
0
}
9106
9107
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9108
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9109
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9110
0
{
9111
    // Mimic 'ignore_char_inputs' logic in InputText()
9112
0
    ImGuiContext& g = *GImGui;
9113
9114
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9115
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9116
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Super));
9117
0
    if (ignore_char_inputs)
9118
0
        return false;
9119
9120
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9121
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9122
0
    return g.KeysMayBeCharInput.TestBit(key);
9123
0
}
9124
9125
// Request a desired route for an input chord (key + mods).
9126
// Return true if the route is available this frame.
9127
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9128
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9129
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9130
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9131
0
{
9132
0
    ImGuiContext& g = *GImGui;
9133
0
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9134
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9135
0
    else
9136
0
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
9137
0
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_None);
9138
9139
    // Convert ImGuiMod_Shortcut and add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9140
0
    key_chord = FixupKeyChord(&g, key_chord);
9141
9142
    // [DEBUG] Debug break requested by user
9143
0
    if (g.DebugBreakInShortcutRouting == key_chord)
9144
0
        IM_DEBUG_BREAK();
9145
9146
0
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9147
0
        if (g.NavWindow == NULL)
9148
0
            return false;
9149
9150
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9151
0
    if (flags & ImGuiInputFlags_RouteAlways)
9152
0
    {
9153
0
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> always\n", GetKeyChordName(key_chord), owner_id, flags);
9154
0
        return true;
9155
0
    }
9156
9157
    // Specific culling when there's an active.
9158
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9159
0
    {
9160
        // Cull shortcuts with no modifiers when it could generate a character.
9161
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9162
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9163
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9164
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9165
0
        if ((flags & ImGuiInputFlags_RouteFocused) && g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9166
0
        {
9167
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> filtered as potential char input\n", GetKeyChordName(key_chord), owner_id, flags);
9168
0
            return false;
9169
0
        }
9170
9171
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9172
0
        if ((flags & ImGuiInputFlags_RouteGlobalHigh) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9173
0
        {
9174
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9175
0
            if (key == ImGuiKey_None)
9176
0
                key = ConvertSingleModFlagToKey(&g, (ImGuiKey)(key_chord & ImGuiMod_Mask_));
9177
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9178
0
                return false;
9179
0
        }
9180
0
    }
9181
9182
    // FIXME-SHORTCUT: A way to configure the location/focus-scope to test would render this more flexible.
9183
0
    const int score = CalcRoutingScore(g.CurrentFocusScopeId, owner_id, flags);
9184
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, owner_id=0x%08X, flags=%04X) -> score %d\n", GetKeyChordName(key_chord), owner_id, flags, score);
9185
0
    if (score == 255)
9186
0
        return false;
9187
9188
    // Submit routing for NEXT frame (assuming score is sufficient)
9189
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9190
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9191
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9192
0
    if (score < routing_data->RoutingNextScore)
9193
0
    {
9194
0
        routing_data->RoutingNext = owner_id;
9195
0
        routing_data->RoutingNextScore = (ImU8)score;
9196
0
    }
9197
9198
    // Return routing state for CURRENT frame
9199
0
    if (routing_data->RoutingCurr == owner_id)
9200
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9201
0
    return routing_data->RoutingCurr == owner_id;
9202
0
}
9203
9204
// Currently unused by core (but used by tests)
9205
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9206
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9207
0
{
9208
0
    ImGuiContext& g = *GImGui;
9209
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9210
0
    key_chord = FixupKeyChord(&g, key_chord);
9211
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9212
0
    return routing_data->RoutingCurr == routing_id;
9213
0
}
9214
9215
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9216
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9217
bool ImGui::IsKeyDown(ImGuiKey key)
9218
0
{
9219
0
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9220
0
}
9221
9222
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9223
0
{
9224
0
    const ImGuiKeyData* key_data = GetKeyData(key);
9225
0
    if (!key_data->Down)
9226
0
        return false;
9227
0
    if (!TestKeyOwner(key, owner_id))
9228
0
        return false;
9229
0
    return true;
9230
0
}
9231
9232
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9233
0
{
9234
0
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9235
0
}
9236
9237
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9238
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9239
0
{
9240
0
    const ImGuiKeyData* key_data = GetKeyData(key);
9241
0
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9242
0
        return false;
9243
0
    const float t = key_data->DownDuration;
9244
0
    if (t < 0.0f)
9245
0
        return false;
9246
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9247
0
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9248
0
        flags |= ImGuiInputFlags_Repeat;
9249
9250
0
    bool pressed = (t == 0.0f);
9251
0
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9252
0
    {
9253
0
        float repeat_delay, repeat_rate;
9254
0
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9255
0
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9256
0
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9257
0
        {
9258
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9259
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9260
0
            ImGuiContext& g = *GImGui;
9261
0
            double key_pressed_time = g.Time - t + 0.00001f;
9262
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9263
0
                pressed = false;
9264
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9265
0
                pressed = false;
9266
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9267
0
                pressed = false;
9268
0
        }
9269
0
    }
9270
0
    if (!pressed)
9271
0
        return false;
9272
0
    if (!TestKeyOwner(key, owner_id))
9273
0
        return false;
9274
0
    return true;
9275
0
}
9276
9277
bool ImGui::IsKeyReleased(ImGuiKey key)
9278
0
{
9279
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9280
0
}
9281
9282
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9283
0
{
9284
0
    const ImGuiKeyData* key_data = GetKeyData(key);
9285
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9286
0
        return false;
9287
0
    if (!TestKeyOwner(key, owner_id))
9288
0
        return false;
9289
0
    return true;
9290
0
}
9291
9292
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9293
0
{
9294
0
    ImGuiContext& g = *GImGui;
9295
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9296
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9297
0
}
9298
9299
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9300
0
{
9301
0
    ImGuiContext& g = *GImGui;
9302
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9303
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9304
0
}
9305
9306
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9307
0
{
9308
0
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9309
0
}
9310
9311
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9312
0
{
9313
0
    ImGuiContext& g = *GImGui;
9314
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9315
0
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9316
0
        return false;
9317
0
    const float t = g.IO.MouseDownDuration[button];
9318
0
    if (t < 0.0f)
9319
0
        return false;
9320
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9321
9322
0
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9323
0
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9324
0
    if (!pressed)
9325
0
        return false;
9326
9327
0
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9328
0
        return false;
9329
9330
0
    return true;
9331
0
}
9332
9333
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9334
0
{
9335
0
    ImGuiContext& g = *GImGui;
9336
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9337
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9338
0
}
9339
9340
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9341
0
{
9342
0
    ImGuiContext& g = *GImGui;
9343
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9344
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9345
0
}
9346
9347
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9348
0
{
9349
0
    ImGuiContext& g = *GImGui;
9350
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9351
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9352
0
}
9353
9354
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9355
0
{
9356
0
    ImGuiContext& g = *GImGui;
9357
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9358
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9359
0
}
9360
9361
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9362
0
{
9363
0
    ImGuiContext& g = *GImGui;
9364
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9365
0
    return g.IO.MouseClickedCount[button];
9366
0
}
9367
9368
// Test if mouse cursor is hovering given rectangle
9369
// NB- Rectangle is clipped by our current clip setting
9370
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9371
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9372
0
{
9373
0
    ImGuiContext& g = *GImGui;
9374
9375
    // Clip
9376
0
    ImRect rect_clipped(r_min, r_max);
9377
0
    if (clip)
9378
0
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9379
9380
    // Hit testing, expanded for touch input
9381
0
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9382
0
        return false;
9383
0
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9384
0
        return false;
9385
0
    return true;
9386
0
}
9387
9388
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9389
// [Internal] This doesn't test if the button is pressed
9390
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9391
0
{
9392
0
    ImGuiContext& g = *GImGui;
9393
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9394
0
    if (lock_threshold < 0.0f)
9395
0
        lock_threshold = g.IO.MouseDragThreshold;
9396
0
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9397
0
}
9398
9399
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9400
0
{
9401
0
    ImGuiContext& g = *GImGui;
9402
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9403
0
    if (!g.IO.MouseDown[button])
9404
0
        return false;
9405
0
    return IsMouseDragPastThreshold(button, lock_threshold);
9406
0
}
9407
9408
ImVec2 ImGui::GetMousePos()
9409
0
{
9410
0
    ImGuiContext& g = *GImGui;
9411
0
    return g.IO.MousePos;
9412
0
}
9413
9414
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9415
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9416
void ImGui::TeleportMousePos(const ImVec2& pos)
9417
0
{
9418
0
    ImGuiContext& g = *GImGui;
9419
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9420
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9421
0
    g.IO.WantSetMousePos = true;
9422
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9423
0
}
9424
9425
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9426
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9427
0
{
9428
0
    ImGuiContext& g = *GImGui;
9429
0
    if (g.BeginPopupStack.Size > 0)
9430
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9431
0
    return g.IO.MousePos;
9432
0
}
9433
9434
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9435
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9436
0
{
9437
    // The assert is only to silence a false-positive in XCode Static Analysis.
9438
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9439
0
    IM_ASSERT(GImGui != NULL);
9440
0
    const float MOUSE_INVALID = -256000.0f;
9441
0
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9442
0
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9443
0
}
9444
9445
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9446
bool ImGui::IsAnyMouseDown()
9447
0
{
9448
0
    ImGuiContext& g = *GImGui;
9449
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9450
0
        if (g.IO.MouseDown[n])
9451
0
            return true;
9452
0
    return false;
9453
0
}
9454
9455
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9456
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9457
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9458
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9459
0
{
9460
0
    ImGuiContext& g = *GImGui;
9461
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9462
0
    if (lock_threshold < 0.0f)
9463
0
        lock_threshold = g.IO.MouseDragThreshold;
9464
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9465
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9466
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9467
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9468
0
    return ImVec2(0.0f, 0.0f);
9469
0
}
9470
9471
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9472
0
{
9473
0
    ImGuiContext& g = *GImGui;
9474
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9475
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9476
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9477
0
}
9478
9479
// Get desired mouse cursor shape.
9480
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9481
// updated during the frame, and locked in EndFrame()/Render().
9482
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9483
ImGuiMouseCursor ImGui::GetMouseCursor()
9484
0
{
9485
0
    ImGuiContext& g = *GImGui;
9486
0
    return g.MouseCursor;
9487
0
}
9488
9489
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9490
0
{
9491
0
    ImGuiContext& g = *GImGui;
9492
0
    g.MouseCursor = cursor_type;
9493
0
}
9494
9495
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9496
0
{
9497
0
    IM_ASSERT(ImGui::IsAliasKey(key));
9498
0
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9499
0
    key_data->Down = v;
9500
0
    key_data->AnalogValue = analog_value;
9501
0
}
9502
9503
// [Internal] Do not use directly
9504
static ImGuiKeyChord GetMergedModsFromKeys()
9505
0
{
9506
0
    ImGuiKeyChord mods = 0;
9507
0
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9508
0
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9509
0
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9510
0
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9511
0
    return mods;
9512
0
}
9513
9514
static void ImGui::UpdateKeyboardInputs()
9515
0
{
9516
0
    ImGuiContext& g = *GImGui;
9517
0
    ImGuiIO& io = g.IO;
9518
9519
    // Import legacy keys or verify they are not used
9520
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9521
    if (io.BackendUsingLegacyKeyArrays == 0)
9522
    {
9523
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9524
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9525
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9526
    }
9527
    else
9528
    {
9529
        if (g.FrameCount == 0)
9530
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9531
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9532
9533
        // Build reverse KeyMap (Named -> Legacy)
9534
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9535
            if (io.KeyMap[n] != -1)
9536
            {
9537
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9538
                io.KeyMap[io.KeyMap[n]] = n;
9539
            }
9540
9541
        // Import legacy keys into new ones
9542
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9543
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9544
            {
9545
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9546
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9547
                io.KeysData[key].Down = io.KeysDown[n];
9548
                if (key != n)
9549
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9550
                io.BackendUsingLegacyKeyArrays = 1;
9551
            }
9552
        if (io.BackendUsingLegacyKeyArrays == 1)
9553
        {
9554
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9555
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9556
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9557
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9558
        }
9559
    }
9560
#endif
9561
9562
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9563
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9564
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9565
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9566
    {
9567
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9568
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9569
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9570
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9571
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9572
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9573
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9574
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9575
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9576
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9577
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9578
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9579
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9580
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9581
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9582
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9583
        #undef NAV_MAP_KEY
9584
    }
9585
#endif
9586
9587
    // Update aliases
9588
0
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9589
0
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9590
0
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9591
0
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9592
9593
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9594
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9595
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9596
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9597
0
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9598
0
    io.KeyMods = GetMergedModsFromKeys();
9599
0
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9600
0
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9601
0
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9602
0
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9603
0
    if (prev_key_mods != io.KeyMods)
9604
0
        g.LastKeyModsChangeTime = g.Time;
9605
0
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9606
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9607
9608
    // Clear gamepad data if disabled
9609
0
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9610
0
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9611
0
        {
9612
0
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9613
0
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9614
0
        }
9615
9616
    // Update keys
9617
0
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9618
0
    {
9619
0
        ImGuiKeyData* key_data = &io.KeysData[i];
9620
0
        key_data->DownDurationPrev = key_data->DownDuration;
9621
0
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9622
0
        if (key_data->DownDuration == 0.0f)
9623
0
        {
9624
0
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9625
0
            if (IsKeyboardKey(key))
9626
0
                g.LastKeyboardKeyPressTime = g.Time;
9627
0
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9628
0
                g.LastKeyboardKeyPressTime = g.Time;
9629
0
        }
9630
0
    }
9631
9632
    // Update keys/input owner (named keys only): one entry per key
9633
0
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9634
0
    {
9635
0
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9636
0
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9637
0
        owner_data->OwnerCurr = owner_data->OwnerNext;
9638
0
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9639
0
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9640
0
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9641
0
    }
9642
9643
    // Update key routing (for e.g. shortcuts)
9644
0
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9645
0
}
9646
9647
static void ImGui::UpdateMouseInputs()
9648
0
{
9649
0
    ImGuiContext& g = *GImGui;
9650
0
    ImGuiIO& io = g.IO;
9651
9652
    // Mouse Wheel swapping flag
9653
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9654
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9655
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9656
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9657
0
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9658
9659
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9660
0
    if (IsMousePosValid(&io.MousePos))
9661
0
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9662
9663
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9664
0
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9665
0
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9666
0
    else
9667
0
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9668
9669
    // Update stationary timer.
9670
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9671
0
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9672
0
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9673
0
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9674
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9675
9676
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9677
0
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9678
0
        g.NavDisableMouseHover = false;
9679
9680
0
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9681
0
    {
9682
0
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9683
0
        io.MouseClickedCount[i] = 0; // Will be filled below
9684
0
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9685
0
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9686
0
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9687
0
        if (io.MouseClicked[i])
9688
0
        {
9689
0
            bool is_repeated_click = false;
9690
0
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9691
0
            {
9692
0
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9693
0
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9694
0
                    is_repeated_click = true;
9695
0
            }
9696
0
            if (is_repeated_click)
9697
0
                io.MouseClickedLastCount[i]++;
9698
0
            else
9699
0
                io.MouseClickedLastCount[i] = 1;
9700
0
            io.MouseClickedTime[i] = g.Time;
9701
0
            io.MouseClickedPos[i] = io.MousePos;
9702
0
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9703
0
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9704
0
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9705
0
        }
9706
0
        else if (io.MouseDown[i])
9707
0
        {
9708
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9709
0
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9710
0
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9711
0
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9712
0
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9713
0
        }
9714
9715
        // We provide io.MouseDoubleClicked[] as a legacy service
9716
0
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9717
9718
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9719
0
        if (io.MouseClicked[i])
9720
0
            g.NavDisableMouseHover = false;
9721
0
    }
9722
0
}
9723
9724
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9725
0
{
9726
0
    ImGuiContext& g = *GImGui;
9727
0
    if (window)
9728
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9729
0
    else
9730
0
        g.WheelingWindowReleaseTimer = 0.0f;
9731
0
    if (g.WheelingWindow == window)
9732
0
        return;
9733
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9734
0
    g.WheelingWindow = window;
9735
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9736
0
    if (window == NULL)
9737
0
    {
9738
0
        g.WheelingWindowStartFrame = -1;
9739
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9740
0
    }
9741
0
}
9742
9743
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9744
0
{
9745
    // For each axis, find window in the hierarchy that may want to use scrolling
9746
0
    ImGuiContext& g = *GImGui;
9747
0
    ImGuiWindow* windows[2] = { NULL, NULL };
9748
0
    for (int axis = 0; axis < 2; axis++)
9749
0
        if (wheel[axis] != 0.0f)
9750
0
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9751
0
            {
9752
                // Bubble up into parent window if:
9753
                // - a child window doesn't allow any scrolling.
9754
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9755
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9756
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9757
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9758
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9759
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9760
0
                    break; // select this window
9761
0
            }
9762
0
    if (windows[0] == NULL && windows[1] == NULL)
9763
0
        return NULL;
9764
9765
    // If there's only one window or only one axis then there's no ambiguity
9766
0
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9767
0
        return windows[1] ? windows[1] : windows[0];
9768
9769
    // If candidate are different windows we need to decide which one to prioritize
9770
    // - First frame: only find a winner if one axis is zero.
9771
    // - Subsequent frames: only find a winner when one is more than the other.
9772
0
    if (g.WheelingWindowStartFrame == -1)
9773
0
        g.WheelingWindowStartFrame = g.FrameCount;
9774
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9775
0
    {
9776
0
        g.WheelingWindowWheelRemainder = wheel;
9777
0
        return NULL;
9778
0
    }
9779
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9780
0
}
9781
9782
// Called by NewFrame()
9783
void ImGui::UpdateMouseWheel()
9784
0
{
9785
    // Reset the locked window if we move the mouse or after the timer elapses.
9786
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9787
0
    ImGuiContext& g = *GImGui;
9788
0
    if (g.WheelingWindow != NULL)
9789
0
    {
9790
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9791
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9792
0
            g.WheelingWindowReleaseTimer = 0.0f;
9793
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9794
0
            LockWheelingWindow(NULL, 0.0f);
9795
0
    }
9796
9797
0
    ImVec2 wheel;
9798
0
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9799
0
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9800
9801
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9802
0
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9803
0
    if (!mouse_window || mouse_window->Collapsed)
9804
0
        return;
9805
9806
    // Zoom / Scale window
9807
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9808
0
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9809
0
    {
9810
0
        LockWheelingWindow(mouse_window, wheel.y);
9811
0
        ImGuiWindow* window = mouse_window;
9812
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9813
0
        const float scale = new_font_scale / window->FontWindowScale;
9814
0
        window->FontWindowScale = new_font_scale;
9815
0
        if (window == window->RootWindow)
9816
0
        {
9817
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9818
0
            SetWindowPos(window, window->Pos + offset, 0);
9819
0
            window->Size = ImTrunc(window->Size * scale);
9820
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
9821
0
        }
9822
0
        return;
9823
0
    }
9824
0
    if (g.IO.KeyCtrl)
9825
0
        return;
9826
9827
    // Mouse wheel scrolling
9828
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9829
0
    if (g.IO.MouseWheelRequestAxisSwap)
9830
0
        wheel = ImVec2(wheel.y, 0.0f);
9831
9832
    // Maintain a rough average of moving magnitude on both axises
9833
    // FIXME: should by based on wall clock time rather than frame-counter
9834
0
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9835
0
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9836
9837
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9838
0
    wheel += g.WheelingWindowWheelRemainder;
9839
0
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9840
0
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9841
0
        return;
9842
9843
    // Mouse wheel scrolling: find target and apply
9844
    // - don't renew lock if axis doesn't apply on the window.
9845
    // - select a main axis when both axises are being moved.
9846
0
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9847
0
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9848
0
        {
9849
0
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9850
0
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9851
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9852
0
            if (do_scroll[ImGuiAxis_X])
9853
0
            {
9854
0
                LockWheelingWindow(window, wheel.x);
9855
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9856
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9857
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9858
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9859
0
            }
9860
0
            if (do_scroll[ImGuiAxis_Y])
9861
0
            {
9862
0
                LockWheelingWindow(window, wheel.y);
9863
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9864
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9865
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9866
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9867
0
            }
9868
0
        }
9869
0
}
9870
9871
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9872
0
{
9873
0
    ImGuiContext& g = *GImGui;
9874
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9875
0
}
9876
9877
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9878
0
{
9879
0
    ImGuiContext& g = *GImGui;
9880
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9881
0
}
9882
9883
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9884
static const char* GetInputSourceName(ImGuiInputSource source)
9885
0
{
9886
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
9887
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9888
0
    return input_source_names[source];
9889
0
}
9890
static const char* GetMouseSourceName(ImGuiMouseSource source)
9891
0
{
9892
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9893
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9894
0
    return mouse_source_names[source];
9895
0
}
9896
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9897
0
{
9898
0
    ImGuiContext& g = *GImGui;
9899
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9900
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9901
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9902
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9903
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9904
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9905
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9906
0
}
9907
#endif
9908
9909
// Process input queue
9910
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9911
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9912
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9913
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9914
0
{
9915
0
    ImGuiContext& g = *GImGui;
9916
0
    ImGuiIO& io = g.IO;
9917
9918
    // Only trickle chars<>key when working with InputText()
9919
    // FIXME: InputText() could parse event trail?
9920
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9921
0
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9922
9923
0
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9924
0
    int  mouse_button_changed = 0x00;
9925
0
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9926
9927
0
    int event_n = 0;
9928
0
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9929
0
    {
9930
0
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9931
0
        if (e->Type == ImGuiInputEventType_MousePos)
9932
0
        {
9933
0
            if (g.IO.WantSetMousePos)
9934
0
                continue;
9935
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9936
0
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9937
0
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9938
0
                break;
9939
0
            io.MousePos = event_pos;
9940
0
            io.MouseSource = e->MousePos.MouseSource;
9941
0
            mouse_moved = true;
9942
0
        }
9943
0
        else if (e->Type == ImGuiInputEventType_MouseButton)
9944
0
        {
9945
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9946
0
            const ImGuiMouseButton button = e->MouseButton.Button;
9947
0
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9948
0
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9949
0
                break;
9950
0
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9951
0
                break;
9952
0
            io.MouseDown[button] = e->MouseButton.Down;
9953
0
            io.MouseSource = e->MouseButton.MouseSource;
9954
0
            mouse_button_changed |= (1 << button);
9955
0
        }
9956
0
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9957
0
        {
9958
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9959
0
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9960
0
                break;
9961
0
            io.MouseWheelH += e->MouseWheel.WheelX;
9962
0
            io.MouseWheel += e->MouseWheel.WheelY;
9963
0
            io.MouseSource = e->MouseWheel.MouseSource;
9964
0
            mouse_wheeled = true;
9965
0
        }
9966
0
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9967
0
        {
9968
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9969
0
        }
9970
0
        else if (e->Type == ImGuiInputEventType_Key)
9971
0
        {
9972
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9973
0
            ImGuiKey key = e->Key.Key;
9974
0
            IM_ASSERT(key != ImGuiKey_None);
9975
0
            ImGuiKeyData* key_data = GetKeyData(key);
9976
0
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9977
0
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9978
0
                break;
9979
0
            key_data->Down = e->Key.Down;
9980
0
            key_data->AnalogValue = e->Key.AnalogValue;
9981
0
            key_changed = true;
9982
0
            key_changed_mask.SetBit(key_data_index);
9983
9984
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9985
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9986
            io.KeysDown[key_data_index] = key_data->Down;
9987
            if (io.KeyMap[key_data_index] != -1)
9988
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9989
#endif
9990
0
        }
9991
0
        else if (e->Type == ImGuiInputEventType_Text)
9992
0
        {
9993
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9994
0
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9995
0
                break;
9996
0
            unsigned int c = e->Text.Char;
9997
0
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9998
0
            if (trickle_interleaved_keys_and_text)
9999
0
                text_inputted = true;
10000
0
        }
10001
0
        else if (e->Type == ImGuiInputEventType_Focus)
10002
0
        {
10003
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10004
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10005
0
            const bool focus_lost = !e->AppFocused.Focused;
10006
0
            io.AppFocusLost = focus_lost;
10007
0
        }
10008
0
        else
10009
0
        {
10010
0
            IM_ASSERT(0 && "Unknown event!");
10011
0
        }
10012
0
    }
10013
10014
    // Record trail (for domain-specific applications wanting to access a precise trail)
10015
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10016
0
    for (int n = 0; n < event_n; n++)
10017
0
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10018
10019
    // [DEBUG]
10020
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10021
0
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10022
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
10023
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10024
0
#endif
10025
10026
    // Remaining events will be processed on the next frame
10027
0
    if (event_n == g.InputEventsQueue.Size)
10028
0
        g.InputEventsQueue.resize(0);
10029
0
    else
10030
0
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10031
10032
    // Clear buttons state when focus is lost
10033
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10034
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10035
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10036
0
    if (g.IO.AppFocusLost)
10037
0
        g.IO.ClearInputKeys();
10038
0
}
10039
10040
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10041
0
{
10042
0
    if (!IsNamedKeyOrModKey(key))
10043
0
        return ImGuiKeyOwner_None;
10044
10045
0
    ImGuiContext& g = *GImGui;
10046
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10047
0
    ImGuiID owner_id = owner_data->OwnerCurr;
10048
10049
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10050
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10051
0
            return ImGuiKeyOwner_None;
10052
10053
0
    return owner_id;
10054
0
}
10055
10056
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10057
// TestKeyOwner(..., None) : (owner == None)
10058
// TestKeyOwner(..., Any)  : no owner test
10059
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10060
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10061
0
{
10062
0
    if (!IsNamedKeyOrModKey(key))
10063
0
        return true;
10064
10065
0
    ImGuiContext& g = *GImGui;
10066
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10067
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10068
0
            return false;
10069
10070
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10071
0
    if (owner_id == ImGuiKeyOwner_Any)
10072
0
        return (owner_data->LockThisFrame == false);
10073
10074
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10075
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10076
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10077
0
    if (owner_data->OwnerCurr != owner_id)
10078
0
    {
10079
0
        if (owner_data->LockThisFrame)
10080
0
            return false;
10081
0
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
10082
0
            return false;
10083
0
    }
10084
10085
0
    return true;
10086
0
}
10087
10088
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10089
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10090
// - SetKeyOwner(..., None)              : clears owner
10091
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10092
// - SetKeyOwner(..., Any or None, Lock) : set lock
10093
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10094
0
{
10095
0
    ImGuiContext& g = *GImGui;
10096
0
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10097
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10098
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10099
10100
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10101
0
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10102
10103
    // We cannot lock by default as it would likely break lots of legacy code.
10104
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10105
0
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10106
0
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10107
0
}
10108
10109
// Rarely used helper
10110
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10111
0
{
10112
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10113
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10114
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10115
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10116
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
10117
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10118
0
}
10119
10120
// This is more or less equivalent to:
10121
//   if (IsItemHovered() || IsItemActive())
10122
//       SetKeyOwner(key, GetItemID());
10123
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10124
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10125
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10126
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10127
0
{
10128
0
    ImGuiContext& g = *GImGui;
10129
0
    ImGuiID id = g.LastItemData.ID;
10130
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10131
0
        return;
10132
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10133
0
        flags |= ImGuiInputFlags_CondDefault_;
10134
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10135
0
    {
10136
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10137
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10138
0
    }
10139
0
}
10140
10141
// This is the only public API until we expose owner_id versions of the API as replacements.
10142
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10143
0
{
10144
0
    return IsKeyChordPressed(key_chord, 0, ImGuiInputFlags_None);
10145
0
}
10146
10147
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10148
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10149
0
{
10150
0
    ImGuiContext& g = *GImGui;
10151
0
    key_chord = FixupKeyChord(&g, key_chord);
10152
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10153
0
    if (g.IO.KeyMods != mods)
10154
0
        return false;
10155
10156
    // Special storage location for mods
10157
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10158
0
    if (key == ImGuiKey_None)
10159
0
        key = ConvertSingleModFlagToKey(&g, mods);
10160
0
    if (!IsKeyPressed(key, owner_id, (flags & ImGuiInputFlags_RepeatMask_)))
10161
0
        return false;
10162
0
    return true;
10163
0
}
10164
10165
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord)
10166
0
{
10167
0
    ImGuiContext& g = *GImGui;
10168
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10169
0
    g.NextItemData.Shortcut = key_chord;
10170
0
}
10171
10172
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10173
0
{
10174
    //ImGuiContext& g = *GImGui;
10175
    //IMGUI_DEBUG_LOG("Shortcut(%s, owner_id=0x%08X, flags=%X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), owner_id, flags);
10176
10177
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10178
0
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
10179
0
        flags |= ImGuiInputFlags_RouteFocused;
10180
10181
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10182
    // Effectively makes Shortcut() always input-owner aware.
10183
0
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_None)
10184
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10185
10186
    // Submit route
10187
0
    if (!SetShortcutRouting(key_chord, owner_id, flags))
10188
0
        return false;
10189
10190
    // Default repeat behavior for Shortcut()
10191
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10192
0
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10193
0
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10194
10195
0
    if (!IsKeyChordPressed(key_chord, owner_id, flags))
10196
0
        return false;
10197
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10198
0
    return true;
10199
0
}
10200
10201
10202
//-----------------------------------------------------------------------------
10203
// [SECTION] ERROR CHECKING
10204
//-----------------------------------------------------------------------------
10205
10206
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
10207
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10208
// If this triggers you have an issue:
10209
// - Most commonly: mismatched headers and compiled code version.
10210
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
10211
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
10212
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
10213
//   Otherwise it is possible that different compilation units would see different structure layout
10214
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10215
0
{
10216
0
    bool error = false;
10217
0
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10218
0
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10219
0
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10220
0
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10221
0
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10222
0
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10223
0
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10224
0
    return !error;
10225
0
}
10226
10227
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10228
// This is causing issues and ambiguity and we need to retire that.
10229
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10230
// [Scenario 1]
10231
//  Previously this would make the window content size ~200x200:
10232
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10233
//  Instead, please submit an item:
10234
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10235
//  Alternative:
10236
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10237
// [Scenario 2]
10238
//  For reference this is one of the issue what we aim to fix with this change:
10239
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10240
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10241
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10242
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10243
0
{
10244
0
    ImGuiContext& g = *GImGui;
10245
0
    ImGuiWindow* window = g.CurrentWindow;
10246
0
    IM_ASSERT(window->DC.IsSetPos);
10247
0
    window->DC.IsSetPos = false;
10248
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10249
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10250
0
        return;
10251
0
    if (window->SkipItems)
10252
0
        return;
10253
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10254
#else
10255
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10256
#endif
10257
0
}
10258
10259
static void ImGui::ErrorCheckNewFrameSanityChecks()
10260
0
{
10261
0
    ImGuiContext& g = *GImGui;
10262
10263
    // Check user IM_ASSERT macro
10264
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10265
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10266
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10267
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10268
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10269
0
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10270
10271
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10272
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10273
#ifdef __EMSCRIPTEN__
10274
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10275
        g.IO.DeltaTime = 0.00001f;
10276
#endif
10277
10278
    // Check user data
10279
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10280
0
    IM_ASSERT(g.Initialized);
10281
0
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10282
0
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10283
0
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10284
0
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10285
0
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10286
0
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10287
0
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10288
0
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10289
0
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10290
0
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10291
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10292
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10293
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10294
10295
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10296
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10297
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10298
#endif
10299
10300
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
10301
0
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10302
0
        g.IO.ConfigWindowsResizeFromEdges = false;
10303
10304
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10305
0
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10306
0
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10307
0
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10308
0
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10309
10310
    // Perform simple checks: multi-viewport and platform windows support
10311
0
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10312
0
    {
10313
0
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10314
0
        {
10315
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10316
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10317
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10318
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10319
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10320
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10321
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10322
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10323
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10324
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10325
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10326
0
        }
10327
0
        else
10328
0
        {
10329
            // Disable feature, our backends do not support it
10330
0
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10331
0
        }
10332
10333
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10334
0
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10335
0
        {
10336
0
            IM_UNUSED(mon);
10337
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10338
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10339
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10340
0
        }
10341
0
    }
10342
0
}
10343
10344
static void ImGui::ErrorCheckEndFrameSanityChecks()
10345
0
{
10346
0
    ImGuiContext& g = *GImGui;
10347
10348
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10349
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10350
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10351
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10352
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10353
    // while still correctly asserting on mid-frame key press events.
10354
0
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10355
0
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10356
0
    IM_UNUSED(key_mods);
10357
10358
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10359
    //ErrorCheckEndFrameRecover();
10360
10361
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10362
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10363
0
    if (g.CurrentWindowStack.Size != 1)
10364
0
    {
10365
0
        if (g.CurrentWindowStack.Size > 1)
10366
0
        {
10367
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10368
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10369
0
            IM_UNUSED(window);
10370
0
            while (g.CurrentWindowStack.Size > 1)
10371
0
                End();
10372
0
        }
10373
0
        else
10374
0
        {
10375
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10376
0
        }
10377
0
    }
10378
10379
0
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10380
0
}
10381
10382
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10383
// Must be called during or before EndFrame().
10384
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10385
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10386
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10387
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10388
0
{
10389
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10390
0
    ImGuiContext& g = *GImGui;
10391
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10392
0
    {
10393
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10394
0
        ImGuiWindow* window = g.CurrentWindow;
10395
0
        if (g.CurrentWindowStack.Size == 1)
10396
0
        {
10397
0
            IM_ASSERT(window->IsFallbackWindow);
10398
0
            break;
10399
0
        }
10400
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10401
0
        {
10402
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10403
0
            EndChild();
10404
0
        }
10405
0
        else
10406
0
        {
10407
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10408
0
            End();
10409
0
        }
10410
0
    }
10411
0
}
10412
10413
// Must be called before End()/EndChild()
10414
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10415
0
{
10416
0
    ImGuiContext& g = *GImGui;
10417
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10418
0
    {
10419
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10420
0
        EndTable();
10421
0
    }
10422
10423
0
    ImGuiWindow* window = g.CurrentWindow;
10424
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10425
0
    IM_ASSERT(window != NULL);
10426
0
    while (g.CurrentTabBar != NULL) //-V1044
10427
0
    {
10428
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10429
0
        EndTabBar();
10430
0
    }
10431
0
    while (window->DC.TreeDepth > 0)
10432
0
    {
10433
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10434
0
        TreePop();
10435
0
    }
10436
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10437
0
    {
10438
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10439
0
        EndGroup();
10440
0
    }
10441
0
    while (window->IDStack.Size > 1)
10442
0
    {
10443
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10444
0
        PopID();
10445
0
    }
10446
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10447
0
    {
10448
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10449
0
        EndDisabled();
10450
0
    }
10451
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10452
0
    {
10453
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10454
0
        PopStyleColor();
10455
0
    }
10456
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10457
0
    {
10458
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10459
0
        PopItemFlag();
10460
0
    }
10461
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10462
0
    {
10463
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10464
0
        PopStyleVar();
10465
0
    }
10466
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10467
0
    {
10468
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10469
0
        PopFont();
10470
0
    }
10471
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10472
0
    {
10473
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10474
0
        PopFocusScope();
10475
0
    }
10476
0
}
10477
10478
// Save current stack sizes for later compare
10479
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10480
0
{
10481
0
    ImGuiContext& g = *ctx;
10482
0
    ImGuiWindow* window = g.CurrentWindow;
10483
0
    SizeOfIDStack = (short)window->IDStack.Size;
10484
0
    SizeOfColorStack = (short)g.ColorStack.Size;
10485
0
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10486
0
    SizeOfFontStack = (short)g.FontStack.Size;
10487
0
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10488
0
    SizeOfGroupStack = (short)g.GroupStack.Size;
10489
0
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10490
0
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10491
0
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10492
0
}
10493
10494
// Compare to detect usage errors
10495
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10496
0
{
10497
0
    ImGuiContext& g = *ctx;
10498
0
    ImGuiWindow* window = g.CurrentWindow;
10499
0
    IM_UNUSED(window);
10500
10501
    // Window stacks
10502
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10503
0
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10504
10505
    // Global stacks
10506
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10507
0
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10508
0
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10509
0
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10510
0
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10511
0
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10512
0
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10513
0
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10514
0
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10515
0
}
10516
10517
//-----------------------------------------------------------------------------
10518
// [SECTION] ITEM SUBMISSION
10519
//-----------------------------------------------------------------------------
10520
// - KeepAliveID()
10521
// - ItemHandleShortcut() [Internal]
10522
// - ItemAdd()
10523
//-----------------------------------------------------------------------------
10524
10525
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10526
void ImGui::KeepAliveID(ImGuiID id)
10527
0
{
10528
0
    ImGuiContext& g = *GImGui;
10529
0
    if (g.ActiveId == id)
10530
0
        g.ActiveIdIsAlive = id;
10531
0
    if (g.ActiveIdPreviousFrame == id)
10532
0
        g.ActiveIdPreviousFrameIsAlive = true;
10533
0
}
10534
10535
static void ItemHandleShortcut(ImGuiID id)
10536
0
{
10537
    // FIXME: Generalize Activation queue?
10538
0
    ImGuiContext& g = *GImGui;
10539
0
    if (ImGui::Shortcut(g.NextItemData.Shortcut, id, ImGuiInputFlags_None) && g.NavActivateId == 0)
10540
0
    {
10541
0
        g.NavActivateId = id; // Will effectively disable clipping.
10542
0
        g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10543
0
        if (g.ActiveId == 0 || g.ActiveId == id)
10544
0
            g.NavActivateDownId = g.NavActivatePressedId = id;
10545
0
        ImGui::NavHighlightActivated(id);
10546
0
    }
10547
0
}
10548
10549
// Declare item bounding box for clipping and interaction.
10550
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10551
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10552
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10553
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10554
0
{
10555
0
    ImGuiContext& g = *GImGui;
10556
0
    ImGuiWindow* window = g.CurrentWindow;
10557
10558
    // Set item data
10559
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10560
0
    g.LastItemData.ID = id;
10561
0
    g.LastItemData.Rect = bb;
10562
0
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10563
0
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10564
0
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10565
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10566
10567
0
    if (id != 0)
10568
0
    {
10569
0
        KeepAliveID(id);
10570
10571
        // Directional navigation processing
10572
        // Runs prior to clipping early-out
10573
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10574
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10575
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10576
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10577
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10578
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10579
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10580
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10581
0
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10582
0
        {
10583
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10584
0
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10585
0
            if (g.NavId == id || g.NavAnyRequest)
10586
0
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10587
0
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10588
0
                        NavProcessItem();
10589
0
        }
10590
10591
0
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10592
0
            ItemHandleShortcut(id);
10593
0
    }
10594
10595
    // Lightweight clear of SetNextItemXXX data.
10596
0
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10597
0
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10598
10599
#ifdef IMGUI_ENABLE_TEST_ENGINE
10600
    if (id != 0)
10601
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10602
#endif
10603
10604
    // Clipping test
10605
    // (this is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10606
    //const bool is_clipped = IsClippedEx(bb, id);
10607
    //if (is_clipped)
10608
    //    return false;
10609
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10610
0
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10611
0
    if (!is_rect_visible)
10612
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10613
0
            if (!g.LogEnabled)
10614
0
                return false;
10615
10616
    // [DEBUG]
10617
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10618
0
    if (id != 0)
10619
0
    {
10620
0
        if (id == g.DebugLocateId)
10621
0
            DebugLocateItemResolveWithLastItem();
10622
10623
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10624
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10625
        // READ THE FAQ: https://dearimgui.com/faq
10626
0
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10627
0
    }
10628
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10629
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10630
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10631
0
#endif
10632
10633
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10634
0
    if (is_rect_visible)
10635
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10636
0
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10637
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10638
0
    return true;
10639
0
}
10640
10641
10642
//-----------------------------------------------------------------------------
10643
// [SECTION] LAYOUT
10644
//-----------------------------------------------------------------------------
10645
// - ItemSize()
10646
// - SameLine()
10647
// - GetCursorScreenPos()
10648
// - SetCursorScreenPos()
10649
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10650
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10651
// - GetCursorStartPos()
10652
// - Indent()
10653
// - Unindent()
10654
// - SetNextItemWidth()
10655
// - PushItemWidth()
10656
// - PushMultiItemsWidths()
10657
// - PopItemWidth()
10658
// - CalcItemWidth()
10659
// - CalcItemSize()
10660
// - GetTextLineHeight()
10661
// - GetTextLineHeightWithSpacing()
10662
// - GetFrameHeight()
10663
// - GetFrameHeightWithSpacing()
10664
// - GetContentRegionMax()
10665
// - GetContentRegionMaxAbs() [Internal]
10666
// - GetContentRegionAvail(),
10667
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10668
// - BeginGroup()
10669
// - EndGroup()
10670
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10671
//-----------------------------------------------------------------------------
10672
10673
// Advance cursor given item size for layout.
10674
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10675
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10676
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
10677
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10678
0
{
10679
0
    ImGuiContext& g = *GImGui;
10680
0
    ImGuiWindow* window = g.CurrentWindow;
10681
0
    if (window->SkipItems)
10682
0
        return;
10683
10684
    // We increase the height in this function to accommodate for baseline offset.
10685
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10686
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10687
0
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10688
10689
0
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10690
0
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10691
10692
    // Always align ourselves on pixel boundaries
10693
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10694
0
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10695
0
    window->DC.CursorPosPrevLine.y = line_y1;
10696
0
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10697
0
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10698
0
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10699
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10700
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10701
10702
0
    window->DC.PrevLineSize.y = line_height;
10703
0
    window->DC.CurrLineSize.y = 0.0f;
10704
0
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10705
0
    window->DC.CurrLineTextBaseOffset = 0.0f;
10706
0
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10707
10708
    // Horizontal layout mode
10709
0
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10710
0
        SameLine();
10711
0
}
10712
10713
// Gets back to previous line and continue with horizontal layout
10714
//      offset_from_start_x == 0 : follow right after previous item
10715
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10716
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10717
//      spacing_w >= 0           : enforce spacing amount
10718
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10719
0
{
10720
0
    ImGuiContext& g = *GImGui;
10721
0
    ImGuiWindow* window = g.CurrentWindow;
10722
0
    if (window->SkipItems)
10723
0
        return;
10724
10725
0
    if (offset_from_start_x != 0.0f)
10726
0
    {
10727
0
        if (spacing_w < 0.0f)
10728
0
            spacing_w = 0.0f;
10729
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10730
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10731
0
    }
10732
0
    else
10733
0
    {
10734
0
        if (spacing_w < 0.0f)
10735
0
            spacing_w = g.Style.ItemSpacing.x;
10736
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10737
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10738
0
    }
10739
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10740
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10741
0
    window->DC.IsSameLine = true;
10742
0
}
10743
10744
ImVec2 ImGui::GetCursorScreenPos()
10745
0
{
10746
0
    ImGuiWindow* window = GetCurrentWindowRead();
10747
0
    return window->DC.CursorPos;
10748
0
}
10749
10750
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10751
0
{
10752
0
    ImGuiWindow* window = GetCurrentWindow();
10753
0
    window->DC.CursorPos = pos;
10754
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10755
0
    window->DC.IsSetPos = true;
10756
0
}
10757
10758
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10759
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10760
ImVec2 ImGui::GetCursorPos()
10761
0
{
10762
0
    ImGuiWindow* window = GetCurrentWindowRead();
10763
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10764
0
}
10765
10766
float ImGui::GetCursorPosX()
10767
0
{
10768
0
    ImGuiWindow* window = GetCurrentWindowRead();
10769
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10770
0
}
10771
10772
float ImGui::GetCursorPosY()
10773
0
{
10774
0
    ImGuiWindow* window = GetCurrentWindowRead();
10775
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10776
0
}
10777
10778
void ImGui::SetCursorPos(const ImVec2& local_pos)
10779
0
{
10780
0
    ImGuiWindow* window = GetCurrentWindow();
10781
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10782
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10783
0
    window->DC.IsSetPos = true;
10784
0
}
10785
10786
void ImGui::SetCursorPosX(float x)
10787
0
{
10788
0
    ImGuiWindow* window = GetCurrentWindow();
10789
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10790
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10791
0
    window->DC.IsSetPos = true;
10792
0
}
10793
10794
void ImGui::SetCursorPosY(float y)
10795
0
{
10796
0
    ImGuiWindow* window = GetCurrentWindow();
10797
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10798
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10799
0
    window->DC.IsSetPos = true;
10800
0
}
10801
10802
ImVec2 ImGui::GetCursorStartPos()
10803
0
{
10804
0
    ImGuiWindow* window = GetCurrentWindowRead();
10805
0
    return window->DC.CursorStartPos - window->Pos;
10806
0
}
10807
10808
void ImGui::Indent(float indent_w)
10809
0
{
10810
0
    ImGuiContext& g = *GImGui;
10811
0
    ImGuiWindow* window = GetCurrentWindow();
10812
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10813
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10814
0
}
10815
10816
void ImGui::Unindent(float indent_w)
10817
0
{
10818
0
    ImGuiContext& g = *GImGui;
10819
0
    ImGuiWindow* window = GetCurrentWindow();
10820
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10821
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10822
0
}
10823
10824
// Affect large frame+labels widgets only.
10825
void ImGui::SetNextItemWidth(float item_width)
10826
0
{
10827
0
    ImGuiContext& g = *GImGui;
10828
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10829
0
    g.NextItemData.Width = item_width;
10830
0
}
10831
10832
// FIXME: Remove the == 0.0f behavior?
10833
void ImGui::PushItemWidth(float item_width)
10834
0
{
10835
0
    ImGuiContext& g = *GImGui;
10836
0
    ImGuiWindow* window = g.CurrentWindow;
10837
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10838
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10839
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10840
0
}
10841
10842
void ImGui::PushMultiItemsWidths(int components, float w_full)
10843
0
{
10844
0
    ImGuiContext& g = *GImGui;
10845
0
    ImGuiWindow* window = g.CurrentWindow;
10846
0
    IM_ASSERT(components > 0);
10847
0
    const ImGuiStyle& style = g.Style;
10848
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10849
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
10850
0
    float prev_split = w_items;
10851
0
    for (int i = components - 1; i > 0; i--)
10852
0
    {
10853
0
        float next_split = IM_TRUNC(w_items * i / components);
10854
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
10855
0
        prev_split = next_split;
10856
0
    }
10857
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
10858
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10859
0
}
10860
10861
void ImGui::PopItemWidth()
10862
0
{
10863
0
    ImGuiWindow* window = GetCurrentWindow();
10864
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10865
0
    window->DC.ItemWidthStack.pop_back();
10866
0
}
10867
10868
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10869
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10870
float ImGui::CalcItemWidth()
10871
0
{
10872
0
    ImGuiContext& g = *GImGui;
10873
0
    ImGuiWindow* window = g.CurrentWindow;
10874
0
    float w;
10875
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10876
0
        w = g.NextItemData.Width;
10877
0
    else
10878
0
        w = window->DC.ItemWidth;
10879
0
    if (w < 0.0f)
10880
0
    {
10881
0
        float region_max_x = GetContentRegionMaxAbs().x;
10882
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10883
0
    }
10884
0
    w = IM_TRUNC(w);
10885
0
    return w;
10886
0
}
10887
10888
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10889
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10890
// Note that only CalcItemWidth() is publicly exposed.
10891
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10892
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10893
0
{
10894
0
    ImGuiContext& g = *GImGui;
10895
0
    ImGuiWindow* window = g.CurrentWindow;
10896
10897
0
    ImVec2 region_max;
10898
0
    if (size.x < 0.0f || size.y < 0.0f)
10899
0
        region_max = GetContentRegionMaxAbs();
10900
10901
0
    if (size.x == 0.0f)
10902
0
        size.x = default_w;
10903
0
    else if (size.x < 0.0f)
10904
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10905
10906
0
    if (size.y == 0.0f)
10907
0
        size.y = default_h;
10908
0
    else if (size.y < 0.0f)
10909
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10910
10911
0
    return size;
10912
0
}
10913
10914
float ImGui::GetTextLineHeight()
10915
0
{
10916
0
    ImGuiContext& g = *GImGui;
10917
0
    return g.FontSize;
10918
0
}
10919
10920
float ImGui::GetTextLineHeightWithSpacing()
10921
0
{
10922
0
    ImGuiContext& g = *GImGui;
10923
0
    return g.FontSize + g.Style.ItemSpacing.y;
10924
0
}
10925
10926
float ImGui::GetFrameHeight()
10927
0
{
10928
0
    ImGuiContext& g = *GImGui;
10929
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10930
0
}
10931
10932
float ImGui::GetFrameHeightWithSpacing()
10933
0
{
10934
0
    ImGuiContext& g = *GImGui;
10935
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10936
0
}
10937
10938
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10939
10940
// FIXME: This is in window space (not screen space!).
10941
ImVec2 ImGui::GetContentRegionMax()
10942
0
{
10943
0
    ImGuiContext& g = *GImGui;
10944
0
    ImGuiWindow* window = g.CurrentWindow;
10945
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10946
0
    return mx - window->Pos;
10947
0
}
10948
10949
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10950
ImVec2 ImGui::GetContentRegionMaxAbs()
10951
0
{
10952
0
    ImGuiContext& g = *GImGui;
10953
0
    ImGuiWindow* window = g.CurrentWindow;
10954
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10955
0
    return mx;
10956
0
}
10957
10958
ImVec2 ImGui::GetContentRegionAvail()
10959
0
{
10960
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10961
0
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10962
0
}
10963
10964
// In window space (not screen space!)
10965
ImVec2 ImGui::GetWindowContentRegionMin()
10966
0
{
10967
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10968
0
    return window->ContentRegionRect.Min - window->Pos;
10969
0
}
10970
10971
ImVec2 ImGui::GetWindowContentRegionMax()
10972
0
{
10973
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10974
0
    return window->ContentRegionRect.Max - window->Pos;
10975
0
}
10976
10977
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10978
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10979
// FIXME-OPT: Could we safely early out on ->SkipItems?
10980
void ImGui::BeginGroup()
10981
0
{
10982
0
    ImGuiContext& g = *GImGui;
10983
0
    ImGuiWindow* window = g.CurrentWindow;
10984
10985
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10986
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10987
0
    group_data.WindowID = window->ID;
10988
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10989
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10990
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10991
0
    group_data.BackupIndent = window->DC.Indent;
10992
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10993
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10994
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10995
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10996
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10997
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
10998
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10999
0
    group_data.EmitItem = true;
11000
11001
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11002
0
    window->DC.Indent = window->DC.GroupOffset;
11003
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
11004
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11005
0
    if (g.LogEnabled)
11006
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11007
0
}
11008
11009
void ImGui::EndGroup()
11010
0
{
11011
0
    ImGuiContext& g = *GImGui;
11012
0
    ImGuiWindow* window = g.CurrentWindow;
11013
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11014
11015
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11016
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11017
11018
0
    if (window->DC.IsSetPos)
11019
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11020
11021
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
11022
11023
0
    window->DC.CursorPos = group_data.BackupCursorPos;
11024
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11025
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
11026
0
    window->DC.Indent = group_data.BackupIndent;
11027
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11028
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11029
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11030
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11031
0
    if (g.LogEnabled)
11032
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11033
11034
0
    if (!group_data.EmitItem)
11035
0
    {
11036
0
        g.GroupStack.pop_back();
11037
0
        return;
11038
0
    }
11039
11040
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11041
0
    ItemSize(group_bb.GetSize());
11042
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11043
11044
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11045
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11046
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11047
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11048
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11049
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11050
0
    if (group_contains_curr_active_id)
11051
0
        g.LastItemData.ID = g.ActiveId;
11052
0
    else if (group_contains_prev_active_id)
11053
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11054
0
    g.LastItemData.Rect = group_bb;
11055
11056
    // Forward Hovered flag
11057
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11058
0
    if (group_contains_curr_hovered_id)
11059
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11060
11061
    // Forward Edited flag
11062
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11063
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11064
11065
    // Forward Deactivated flag
11066
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11067
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11068
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11069
11070
0
    g.GroupStack.pop_back();
11071
0
    if (g.DebugShowGroupRects)
11072
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11073
0
}
11074
11075
11076
//-----------------------------------------------------------------------------
11077
// [SECTION] SCROLLING
11078
//-----------------------------------------------------------------------------
11079
11080
// Helper to snap on edges when aiming at an item very close to the edge,
11081
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11082
// When we refactor the scrolling API this may be configurable with a flag?
11083
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11084
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11085
0
{
11086
0
    if (target <= snap_min + snap_threshold)
11087
0
        return ImLerp(snap_min, target, center_ratio);
11088
0
    if (target >= snap_max - snap_threshold)
11089
0
        return ImLerp(target, snap_max, center_ratio);
11090
0
    return target;
11091
0
}
11092
11093
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11094
0
{
11095
0
    ImVec2 scroll = window->Scroll;
11096
0
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11097
0
    for (int axis = 0; axis < 2; axis++)
11098
0
    {
11099
0
        if (window->ScrollTarget[axis] < FLT_MAX)
11100
0
        {
11101
0
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11102
0
            float scroll_target = window->ScrollTarget[axis];
11103
0
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11104
0
            {
11105
0
                float snap_min = 0.0f;
11106
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11107
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11108
0
            }
11109
0
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11110
0
        }
11111
0
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11112
0
        if (!window->Collapsed && !window->SkipItems)
11113
0
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11114
0
    }
11115
0
    return scroll;
11116
0
}
11117
11118
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11119
0
{
11120
0
    ImGuiContext& g = *GImGui;
11121
0
    ImGuiWindow* window = g.CurrentWindow;
11122
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11123
0
}
11124
11125
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11126
0
{
11127
0
    ScrollToRectEx(window, item_rect, flags);
11128
0
}
11129
11130
// Scroll to keep newly navigated item fully into view
11131
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11132
0
{
11133
0
    ImGuiContext& g = *GImGui;
11134
0
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11135
0
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11136
0
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11137
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11138
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11139
11140
    // Check that only one behavior is selected per axis
11141
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11142
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11143
11144
    // Defaults
11145
0
    ImGuiScrollFlags in_flags = flags;
11146
0
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11147
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11148
0
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11149
0
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11150
11151
0
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11152
0
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11153
0
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11154
0
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11155
11156
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11157
0
    {
11158
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11159
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11160
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11161
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11162
0
    }
11163
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11164
0
    {
11165
0
        if (can_be_fully_visible_x)
11166
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11167
0
        else
11168
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11169
0
    }
11170
11171
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11172
0
    {
11173
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11174
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11175
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11176
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11177
0
    }
11178
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11179
0
    {
11180
0
        if (can_be_fully_visible_y)
11181
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11182
0
        else
11183
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11184
0
    }
11185
11186
0
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11187
0
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11188
11189
    // Also scroll parent window to keep us into view if necessary
11190
0
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11191
0
    {
11192
        // FIXME-SCROLL: May be an option?
11193
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11194
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11195
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11196
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11197
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11198
0
    }
11199
11200
0
    return delta_scroll;
11201
0
}
11202
11203
float ImGui::GetScrollX()
11204
0
{
11205
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11206
0
    return window->Scroll.x;
11207
0
}
11208
11209
float ImGui::GetScrollY()
11210
0
{
11211
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11212
0
    return window->Scroll.y;
11213
0
}
11214
11215
float ImGui::GetScrollMaxX()
11216
0
{
11217
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11218
0
    return window->ScrollMax.x;
11219
0
}
11220
11221
float ImGui::GetScrollMaxY()
11222
0
{
11223
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11224
0
    return window->ScrollMax.y;
11225
0
}
11226
11227
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11228
0
{
11229
0
    window->ScrollTarget.x = scroll_x;
11230
0
    window->ScrollTargetCenterRatio.x = 0.0f;
11231
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11232
0
}
11233
11234
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11235
0
{
11236
0
    window->ScrollTarget.y = scroll_y;
11237
0
    window->ScrollTargetCenterRatio.y = 0.0f;
11238
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11239
0
}
11240
11241
void ImGui::SetScrollX(float scroll_x)
11242
0
{
11243
0
    ImGuiContext& g = *GImGui;
11244
0
    SetScrollX(g.CurrentWindow, scroll_x);
11245
0
}
11246
11247
void ImGui::SetScrollY(float scroll_y)
11248
0
{
11249
0
    ImGuiContext& g = *GImGui;
11250
0
    SetScrollY(g.CurrentWindow, scroll_y);
11251
0
}
11252
11253
// Note that a local position will vary depending on initial scroll value,
11254
// This is a little bit confusing so bear with us:
11255
//  - local_pos = (absolution_pos - window->Pos)
11256
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11257
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11258
//  - They mostly exist because of legacy API.
11259
// Following the rules above, when trying to work with scrolling code, consider that:
11260
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11261
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11262
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11263
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11264
0
{
11265
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11266
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11267
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11268
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11269
0
}
11270
11271
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11272
0
{
11273
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11274
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11275
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11276
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11277
0
}
11278
11279
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11280
0
{
11281
0
    ImGuiContext& g = *GImGui;
11282
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11283
0
}
11284
11285
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11286
0
{
11287
0
    ImGuiContext& g = *GImGui;
11288
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11289
0
}
11290
11291
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11292
void ImGui::SetScrollHereX(float center_x_ratio)
11293
0
{
11294
0
    ImGuiContext& g = *GImGui;
11295
0
    ImGuiWindow* window = g.CurrentWindow;
11296
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11297
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11298
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11299
11300
    // Tweak: snap on edges when aiming at an item very close to the edge
11301
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11302
0
}
11303
11304
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11305
void ImGui::SetScrollHereY(float center_y_ratio)
11306
0
{
11307
0
    ImGuiContext& g = *GImGui;
11308
0
    ImGuiWindow* window = g.CurrentWindow;
11309
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11310
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11311
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11312
11313
    // Tweak: snap on edges when aiming at an item very close to the edge
11314
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11315
0
}
11316
11317
//-----------------------------------------------------------------------------
11318
// [SECTION] TOOLTIPS
11319
//-----------------------------------------------------------------------------
11320
11321
bool ImGui::BeginTooltip()
11322
0
{
11323
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11324
0
}
11325
11326
bool ImGui::BeginItemTooltip()
11327
0
{
11328
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11329
0
        return false;
11330
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11331
0
}
11332
11333
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11334
0
{
11335
0
    ImGuiContext& g = *GImGui;
11336
11337
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11338
0
    {
11339
        // Drag and Drop tooltips are positioning differently than other tooltips:
11340
        // - offset visibility to increase visibility around mouse.
11341
        // - never clamp within outer viewport boundary.
11342
        // We call SetNextWindowPos() to enforce position and disable clamping.
11343
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11344
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11345
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11346
0
        SetNextWindowPos(tooltip_pos);
11347
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11348
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11349
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11350
0
    }
11351
11352
0
    char window_name[16];
11353
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11354
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11355
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11356
0
            if (window->Active)
11357
0
            {
11358
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11359
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11360
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11361
0
            }
11362
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11363
0
    Begin(window_name, NULL, flags | extra_window_flags);
11364
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11365
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11366
    //if (!ret)
11367
    //    End();
11368
    //return ret;
11369
0
    return true;
11370
0
}
11371
11372
void ImGui::EndTooltip()
11373
0
{
11374
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11375
0
    End();
11376
0
}
11377
11378
void ImGui::SetTooltip(const char* fmt, ...)
11379
0
{
11380
0
    va_list args;
11381
0
    va_start(args, fmt);
11382
0
    SetTooltipV(fmt, args);
11383
0
    va_end(args);
11384
0
}
11385
11386
void ImGui::SetTooltipV(const char* fmt, va_list args)
11387
0
{
11388
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11389
0
        return;
11390
0
    TextV(fmt, args);
11391
0
    EndTooltip();
11392
0
}
11393
11394
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11395
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11396
void ImGui::SetItemTooltip(const char* fmt, ...)
11397
0
{
11398
0
    va_list args;
11399
0
    va_start(args, fmt);
11400
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11401
0
        SetTooltipV(fmt, args);
11402
0
    va_end(args);
11403
0
}
11404
11405
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11406
0
{
11407
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11408
0
        SetTooltipV(fmt, args);
11409
0
}
11410
11411
11412
//-----------------------------------------------------------------------------
11413
// [SECTION] POPUPS
11414
//-----------------------------------------------------------------------------
11415
11416
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11417
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11418
0
{
11419
0
    ImGuiContext& g = *GImGui;
11420
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11421
0
    {
11422
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11423
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11424
0
        IM_ASSERT(id == 0);
11425
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11426
0
            return g.OpenPopupStack.Size > 0;
11427
0
        else
11428
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11429
0
    }
11430
0
    else
11431
0
    {
11432
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11433
0
        {
11434
            // Return true if the popup is open anywhere in the popup stack
11435
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11436
0
                if (popup_data.PopupId == id)
11437
0
                    return true;
11438
0
            return false;
11439
0
        }
11440
0
        else
11441
0
        {
11442
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11443
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11444
0
        }
11445
0
    }
11446
0
}
11447
11448
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11449
0
{
11450
0
    ImGuiContext& g = *GImGui;
11451
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11452
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11453
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11454
0
    return IsPopupOpen(id, popup_flags);
11455
0
}
11456
11457
// Also see FindBlockingModal(NULL)
11458
ImGuiWindow* ImGui::GetTopMostPopupModal()
11459
0
{
11460
0
    ImGuiContext& g = *GImGui;
11461
0
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11462
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11463
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11464
0
                return popup;
11465
0
    return NULL;
11466
0
}
11467
11468
// See Demo->Stacked Modal to confirm what this is for.
11469
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11470
0
{
11471
0
    ImGuiContext& g = *GImGui;
11472
0
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11473
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11474
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11475
0
                return popup;
11476
0
    return NULL;
11477
0
}
11478
11479
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11480
0
{
11481
0
    ImGuiContext& g = *GImGui;
11482
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11483
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11484
0
    OpenPopupEx(id, popup_flags);
11485
0
}
11486
11487
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11488
0
{
11489
0
    OpenPopupEx(id, popup_flags);
11490
0
}
11491
11492
// Mark popup as open (toggle toward open state).
11493
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11494
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11495
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11496
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11497
0
{
11498
0
    ImGuiContext& g = *GImGui;
11499
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11500
0
    const int current_stack_size = g.BeginPopupStack.Size;
11501
11502
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11503
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11504
0
            return;
11505
11506
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11507
0
    popup_ref.PopupId = id;
11508
0
    popup_ref.Window = NULL;
11509
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11510
0
    popup_ref.OpenFrameCount = g.FrameCount;
11511
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11512
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11513
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11514
11515
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11516
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11517
0
    {
11518
0
        g.OpenPopupStack.push_back(popup_ref);
11519
0
    }
11520
0
    else
11521
0
    {
11522
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11523
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11524
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11525
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11526
0
        bool keep_existing = false;
11527
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11528
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11529
0
                keep_existing = true;
11530
0
        if (keep_existing)
11531
0
        {
11532
            // No reopen
11533
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11534
0
        }
11535
0
        else
11536
0
        {
11537
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11538
0
            ClosePopupToLevel(current_stack_size, true);
11539
0
            g.OpenPopupStack.push_back(popup_ref);
11540
0
        }
11541
11542
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11543
        // This is equivalent to what ClosePopupToLevel() does.
11544
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11545
        //    FocusWindow(parent_window);
11546
0
    }
11547
0
}
11548
11549
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11550
// This function closes any popups that are over 'ref_window'.
11551
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11552
0
{
11553
0
    ImGuiContext& g = *GImGui;
11554
0
    if (g.OpenPopupStack.Size == 0)
11555
0
        return;
11556
11557
    // Don't close our own child popup windows.
11558
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11559
0
    int popup_count_to_keep = 0;
11560
0
    if (ref_window)
11561
0
    {
11562
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11563
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11564
0
        {
11565
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11566
0
            if (!popup.Window)
11567
0
                continue;
11568
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11569
11570
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11571
            // - Clicking/Focusing Window2 won't close Popup1:
11572
            //     Window -> Popup1 -> Window2(Ref)
11573
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11574
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11575
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11576
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11577
            // We step through every popup from bottom to top to validate their position relative to reference window.
11578
0
            bool ref_window_is_descendent_of_popup = false;
11579
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11580
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11581
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11582
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11583
0
                    {
11584
0
                        ref_window_is_descendent_of_popup = true;
11585
0
                        break;
11586
0
                    }
11587
0
            if (!ref_window_is_descendent_of_popup)
11588
0
                break;
11589
0
        }
11590
0
    }
11591
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11592
0
    {
11593
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11594
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11595
0
    }
11596
0
}
11597
11598
void ImGui::ClosePopupsExceptModals()
11599
0
{
11600
0
    ImGuiContext& g = *GImGui;
11601
11602
0
    int popup_count_to_keep;
11603
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11604
0
    {
11605
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11606
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11607
0
            break;
11608
0
    }
11609
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11610
0
        ClosePopupToLevel(popup_count_to_keep, true);
11611
0
}
11612
11613
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11614
0
{
11615
0
    ImGuiContext& g = *GImGui;
11616
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11617
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11618
11619
    // Trim open popup stack
11620
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11621
0
    g.OpenPopupStack.resize(remaining);
11622
11623
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11624
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11625
0
    {
11626
0
        ImGuiWindow* popup_window = prev_popup.Window;
11627
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11628
0
        if (focus_window && !focus_window->WasActive)
11629
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11630
0
        else
11631
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11632
0
    }
11633
0
}
11634
11635
// Close the popup we have begin-ed into.
11636
void ImGui::CloseCurrentPopup()
11637
0
{
11638
0
    ImGuiContext& g = *GImGui;
11639
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11640
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11641
0
        return;
11642
11643
    // Closing a menu closes its top-most parent popup (unless a modal)
11644
0
    while (popup_idx > 0)
11645
0
    {
11646
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11647
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11648
0
        bool close_parent = false;
11649
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11650
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11651
0
                close_parent = true;
11652
0
        if (!close_parent)
11653
0
            break;
11654
0
        popup_idx--;
11655
0
    }
11656
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11657
0
    ClosePopupToLevel(popup_idx, true);
11658
11659
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11660
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11661
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11662
0
    if (ImGuiWindow* window = g.NavWindow)
11663
0
        window->DC.NavHideHighlightOneFrame = true;
11664
0
}
11665
11666
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11667
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11668
0
{
11669
0
    ImGuiContext& g = *GImGui;
11670
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11671
0
    {
11672
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11673
0
        return false;
11674
0
    }
11675
11676
0
    char name[20];
11677
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11678
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
11679
0
    else
11680
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11681
11682
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11683
0
    bool is_open = Begin(name, NULL, flags);
11684
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11685
0
        EndPopup();
11686
11687
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
11688
11689
0
    return is_open;
11690
0
}
11691
11692
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11693
0
{
11694
0
    ImGuiContext& g = *GImGui;
11695
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11696
0
    {
11697
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11698
0
        return false;
11699
0
    }
11700
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11701
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11702
0
    return BeginPopupEx(id, flags);
11703
0
}
11704
11705
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11706
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11707
// - *p_open set back to false in BeginPopupModal() when popup is not open.
11708
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11709
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11710
0
{
11711
0
    ImGuiContext& g = *GImGui;
11712
0
    ImGuiWindow* window = g.CurrentWindow;
11713
0
    const ImGuiID id = window->GetID(name);
11714
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11715
0
    {
11716
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11717
0
        if (p_open && *p_open)
11718
0
            *p_open = false;
11719
0
        return false;
11720
0
    }
11721
11722
    // Center modal windows by default for increased visibility
11723
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11724
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11725
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11726
0
    {
11727
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11728
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11729
0
    }
11730
11731
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11732
0
    const bool is_open = Begin(name, p_open, flags);
11733
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11734
0
    {
11735
0
        EndPopup();
11736
0
        if (is_open)
11737
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11738
0
        return false;
11739
0
    }
11740
0
    return is_open;
11741
0
}
11742
11743
void ImGui::EndPopup()
11744
0
{
11745
0
    ImGuiContext& g = *GImGui;
11746
0
    ImGuiWindow* window = g.CurrentWindow;
11747
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11748
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11749
11750
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11751
0
    if (g.NavWindow == window)
11752
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11753
11754
    // Child-popups don't need to be laid out
11755
0
    IM_ASSERT(g.WithinEndChild == false);
11756
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11757
0
        g.WithinEndChild = true;
11758
0
    End();
11759
0
    g.WithinEndChild = false;
11760
0
}
11761
11762
// Helper to open a popup if mouse button is released over the item
11763
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11764
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11765
0
{
11766
0
    ImGuiContext& g = *GImGui;
11767
0
    ImGuiWindow* window = g.CurrentWindow;
11768
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11769
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11770
0
    {
11771
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11772
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11773
0
        OpenPopupEx(id, popup_flags);
11774
0
    }
11775
0
}
11776
11777
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11778
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11779
// - To create a popup with a specific identifier, pass it in str_id.
11780
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11781
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11782
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11783
//   This is essentially the same as:
11784
//       id = str_id ? GetID(str_id) : GetItemID();
11785
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11786
//       return BeginPopup(id);
11787
//   Which is essentially the same as:
11788
//       id = str_id ? GetID(str_id) : GetItemID();
11789
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11790
//           OpenPopup(id);
11791
//       return BeginPopup(id);
11792
//   The main difference being that this is tweaked to avoid computing the ID twice.
11793
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11794
0
{
11795
0
    ImGuiContext& g = *GImGui;
11796
0
    ImGuiWindow* window = g.CurrentWindow;
11797
0
    if (window->SkipItems)
11798
0
        return false;
11799
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11800
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11801
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11802
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11803
0
        OpenPopupEx(id, popup_flags);
11804
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11805
0
}
11806
11807
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11808
0
{
11809
0
    ImGuiContext& g = *GImGui;
11810
0
    ImGuiWindow* window = g.CurrentWindow;
11811
0
    if (!str_id)
11812
0
        str_id = "window_context";
11813
0
    ImGuiID id = window->GetID(str_id);
11814
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11815
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11816
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11817
0
            OpenPopupEx(id, popup_flags);
11818
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11819
0
}
11820
11821
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11822
0
{
11823
0
    ImGuiContext& g = *GImGui;
11824
0
    ImGuiWindow* window = g.CurrentWindow;
11825
0
    if (!str_id)
11826
0
        str_id = "void_context";
11827
0
    ImGuiID id = window->GetID(str_id);
11828
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11829
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11830
0
        if (GetTopMostPopupModal() == NULL)
11831
0
            OpenPopupEx(id, popup_flags);
11832
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11833
0
}
11834
11835
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11836
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11837
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11838
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11839
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11840
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11841
0
{
11842
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11843
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11844
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11845
11846
    // Combo Box policy (we want a connecting edge)
11847
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11848
0
    {
11849
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11850
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11851
0
        {
11852
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11853
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11854
0
                continue;
11855
0
            ImVec2 pos;
11856
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11857
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11858
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11859
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11860
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11861
0
                continue;
11862
0
            *last_dir = dir;
11863
0
            return pos;
11864
0
        }
11865
0
    }
11866
11867
    // Tooltip and Default popup policy
11868
    // (Always first try the direction we used on the last frame, if any)
11869
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11870
0
    {
11871
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11872
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11873
0
        {
11874
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11875
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11876
0
                continue;
11877
11878
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11879
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11880
11881
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11882
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11883
0
                continue;
11884
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11885
0
                continue;
11886
11887
0
            ImVec2 pos;
11888
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11889
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11890
11891
            // Clamp top-left corner of popup
11892
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11893
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11894
11895
0
            *last_dir = dir;
11896
0
            return pos;
11897
0
        }
11898
0
    }
11899
11900
    // Fallback when not enough room:
11901
0
    *last_dir = ImGuiDir_None;
11902
11903
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11904
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11905
0
        return ref_pos + ImVec2(2, 2);
11906
11907
    // Otherwise try to keep within display
11908
0
    ImVec2 pos = ref_pos;
11909
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11910
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11911
0
    return pos;
11912
0
}
11913
11914
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11915
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11916
0
{
11917
0
    ImGuiContext& g = *GImGui;
11918
0
    ImRect r_screen;
11919
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11920
0
    {
11921
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11922
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11923
0
        r_screen.Min = monitor.WorkPos;
11924
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11925
0
    }
11926
0
    else
11927
0
    {
11928
        // Use the full viewport area (not work area) for popups
11929
0
        r_screen = window->Viewport->GetMainRect();
11930
0
    }
11931
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11932
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11933
0
    return r_screen;
11934
0
}
11935
11936
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11937
0
{
11938
0
    ImGuiContext& g = *GImGui;
11939
11940
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11941
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11942
0
    {
11943
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11944
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11945
0
        ImGuiWindow* parent_window = window->ParentWindow;
11946
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11947
0
        ImRect r_avoid;
11948
0
        if (parent_window->DC.MenuBarAppending)
11949
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11950
0
        else
11951
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11952
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11953
0
    }
11954
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11955
0
    {
11956
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11957
0
    }
11958
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11959
0
    {
11960
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11961
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11962
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11963
0
        IM_ASSERT(g.CurrentWindow == window);
11964
0
        const float scale = g.Style.MouseCursorScale;
11965
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11966
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11967
0
        ImRect r_avoid;
11968
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11969
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11970
0
        else
11971
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11972
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11973
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11974
0
    }
11975
0
    IM_ASSERT(0);
11976
0
    return window->Pos;
11977
0
}
11978
11979
//-----------------------------------------------------------------------------
11980
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11981
//-----------------------------------------------------------------------------
11982
11983
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11984
// In our terminology those should be interchangeable, yet right now this is super confusing.
11985
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11986
11987
void ImGui::SetNavWindow(ImGuiWindow* window)
11988
0
{
11989
0
    ImGuiContext& g = *GImGui;
11990
0
    if (g.NavWindow != window)
11991
0
    {
11992
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11993
0
        g.NavWindow = window;
11994
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11995
0
    }
11996
0
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11997
0
    NavUpdateAnyRequestFlag();
11998
0
}
11999
12000
void ImGui::NavHighlightActivated(ImGuiID id)
12001
0
{
12002
0
    ImGuiContext& g = *GImGui;
12003
0
    g.NavHighlightActivatedId = id;
12004
0
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12005
0
}
12006
12007
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12008
0
{
12009
0
    ImGuiContext& g = *GImGui;
12010
0
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12011
0
}
12012
12013
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12014
0
{
12015
0
    ImGuiContext& g = *GImGui;
12016
0
    IM_ASSERT(g.NavWindow != NULL);
12017
0
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12018
0
    g.NavId = id;
12019
0
    g.NavLayer = nav_layer;
12020
0
    SetNavFocusScope(focus_scope_id);
12021
0
    g.NavWindow->NavLastIds[nav_layer] = id;
12022
0
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12023
12024
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12025
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12026
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12027
0
}
12028
12029
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12030
0
{
12031
0
    ImGuiContext& g = *GImGui;
12032
0
    IM_ASSERT(id != 0);
12033
12034
0
    if (g.NavWindow != window)
12035
0
       SetNavWindow(window);
12036
12037
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12038
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12039
0
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12040
0
    g.NavId = id;
12041
0
    g.NavLayer = nav_layer;
12042
0
    SetNavFocusScope(g.CurrentFocusScopeId);
12043
0
    window->NavLastIds[nav_layer] = id;
12044
0
    if (g.LastItemData.ID == id)
12045
0
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12046
12047
0
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12048
0
        g.NavDisableMouseHover = true;
12049
0
    else
12050
0
        g.NavDisableHighlight = true;
12051
12052
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12053
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12054
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12055
0
}
12056
12057
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12058
0
{
12059
0
    if (ImFabs(dx) > ImFabs(dy))
12060
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12061
0
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12062
0
}
12063
12064
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12065
0
{
12066
0
    if (cand_max < curr_min)
12067
0
        return cand_max - curr_min;
12068
0
    if (curr_max < cand_min)
12069
0
        return cand_min - curr_max;
12070
0
    return 0.0f;
12071
0
}
12072
12073
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12074
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12075
0
{
12076
0
    ImGuiContext& g = *GImGui;
12077
0
    ImGuiWindow* window = g.CurrentWindow;
12078
0
    if (g.NavLayer != window->DC.NavLayerCurrent)
12079
0
        return false;
12080
12081
    // FIXME: Those are not good variables names
12082
0
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12083
0
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12084
0
    g.NavScoringDebugCount++;
12085
12086
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12087
0
    if (window->ParentWindow == g.NavWindow)
12088
0
    {
12089
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
12090
0
        if (!window->ClipRect.Overlaps(cand))
12091
0
            return false;
12092
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12093
0
    }
12094
12095
    // Compute distance between boxes
12096
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12097
0
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12098
0
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12099
0
    if (dby != 0.0f && dbx != 0.0f)
12100
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12101
0
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12102
12103
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12104
0
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12105
0
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12106
0
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12107
12108
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12109
0
    ImGuiDir quadrant;
12110
0
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12111
0
    if (dbx != 0.0f || dby != 0.0f)
12112
0
    {
12113
        // For non-overlapping boxes, use distance between boxes
12114
0
        dax = dbx;
12115
0
        day = dby;
12116
0
        dist_axial = dist_box;
12117
0
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12118
0
    }
12119
0
    else if (dcx != 0.0f || dcy != 0.0f)
12120
0
    {
12121
        // For overlapping boxes with different centers, use distance between centers
12122
0
        dax = dcx;
12123
0
        day = dcy;
12124
0
        dist_axial = dist_center;
12125
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12126
0
    }
12127
0
    else
12128
0
    {
12129
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12130
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12131
0
    }
12132
12133
0
    const ImGuiDir move_dir = g.NavMoveDir;
12134
#if IMGUI_DEBUG_NAV_SCORING
12135
    char buf[200];
12136
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12137
    {
12138
        if (quadrant == move_dir)
12139
        {
12140
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12141
            ImDrawList* draw_list = GetForegroundDrawList(window);
12142
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12143
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12144
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12145
        }
12146
    }
12147
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12148
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12149
    if (debug_hovering || debug_tty)
12150
    {
12151
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12152
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12153
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12154
        if (debug_hovering)
12155
        {
12156
            ImDrawList* draw_list = GetForegroundDrawList(window);
12157
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12158
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12159
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12160
            draw_list->AddText(cand.Max, ~0U, buf);
12161
        }
12162
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12163
    }
12164
#endif
12165
12166
    // Is it in the quadrant we're interested in moving to?
12167
0
    bool new_best = false;
12168
0
    if (quadrant == move_dir)
12169
0
    {
12170
        // Does it beat the current best candidate?
12171
0
        if (dist_box < result->DistBox)
12172
0
        {
12173
0
            result->DistBox = dist_box;
12174
0
            result->DistCenter = dist_center;
12175
0
            return true;
12176
0
        }
12177
0
        if (dist_box == result->DistBox)
12178
0
        {
12179
            // Try using distance between center points to break ties
12180
0
            if (dist_center < result->DistCenter)
12181
0
            {
12182
0
                result->DistCenter = dist_center;
12183
0
                new_best = true;
12184
0
            }
12185
0
            else if (dist_center == result->DistCenter)
12186
0
            {
12187
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12188
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12189
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12190
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12191
0
                    new_best = true;
12192
0
            }
12193
0
        }
12194
0
    }
12195
12196
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12197
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12198
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12199
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12200
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12201
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12202
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12203
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12204
0
            {
12205
0
                result->DistAxial = dist_axial;
12206
0
                new_best = true;
12207
0
            }
12208
12209
0
    return new_best;
12210
0
}
12211
12212
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12213
0
{
12214
0
    ImGuiContext& g = *GImGui;
12215
0
    ImGuiWindow* window = g.CurrentWindow;
12216
0
    result->Window = window;
12217
0
    result->ID = g.LastItemData.ID;
12218
0
    result->FocusScopeId = g.CurrentFocusScopeId;
12219
0
    result->InFlags = g.LastItemData.InFlags;
12220
0
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12221
0
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12222
0
    {
12223
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12224
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12225
0
    }
12226
0
}
12227
12228
// True when current work location may be scrolled horizontally when moving left / right.
12229
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12230
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12231
0
{
12232
0
    ImGuiContext& g = *GImGui;
12233
0
    ImGuiWindow* window = g.CurrentWindow;
12234
0
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12235
0
}
12236
12237
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12238
// This is called after LastItemData is set, but NextItemData is also still valid.
12239
static void ImGui::NavProcessItem()
12240
0
{
12241
0
    ImGuiContext& g = *GImGui;
12242
0
    ImGuiWindow* window = g.CurrentWindow;
12243
0
    const ImGuiID id = g.LastItemData.ID;
12244
0
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12245
12246
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12247
0
    if (window->DC.NavIsScrollPushableX == false)
12248
0
    {
12249
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12250
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12251
0
    }
12252
0
    const ImRect nav_bb = g.LastItemData.NavRect;
12253
12254
    // Process Init Request
12255
0
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12256
0
    {
12257
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12258
0
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12259
0
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12260
0
        {
12261
0
            NavApplyItemToResult(&g.NavInitResult);
12262
0
        }
12263
0
        if (candidate_for_nav_default_focus)
12264
0
        {
12265
0
            g.NavInitRequest = false; // Found a match, clear request
12266
0
            NavUpdateAnyRequestFlag();
12267
0
        }
12268
0
    }
12269
12270
    // Process Move Request (scoring for navigation)
12271
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12272
0
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12273
0
    {
12274
0
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12275
0
        {
12276
0
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12277
0
            if (is_tabbing)
12278
0
            {
12279
0
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12280
0
            }
12281
0
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12282
0
            {
12283
0
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12284
0
                if (NavScoreItem(result))
12285
0
                    NavApplyItemToResult(result);
12286
12287
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12288
0
                const float VISIBLE_RATIO = 0.70f;
12289
0
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12290
0
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12291
0
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12292
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12293
0
            }
12294
0
        }
12295
0
    }
12296
12297
    // Update information for currently focused/navigated item
12298
0
    if (g.NavId == id)
12299
0
    {
12300
0
        if (g.NavWindow != window)
12301
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12302
0
        g.NavLayer = window->DC.NavLayerCurrent;
12303
0
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12304
0
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12305
0
        g.NavIdIsAlive = true;
12306
0
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12307
0
        {
12308
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12309
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12310
0
        }
12311
0
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12312
0
    }
12313
0
}
12314
12315
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12316
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12317
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12318
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12319
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12320
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12321
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12322
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12323
0
{
12324
0
    ImGuiContext& g = *GImGui;
12325
12326
0
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12327
0
    {
12328
0
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12329
0
            return;
12330
0
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12331
0
            return;
12332
0
    }
12333
12334
    // - Can always land on an item when using API call.
12335
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12336
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12337
0
    bool can_stop;
12338
0
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12339
0
        can_stop = true;
12340
0
    else
12341
0
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12342
12343
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12344
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12345
0
    if (g.NavTabbingDir == +1)
12346
0
    {
12347
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12348
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12349
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12350
0
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12351
0
            NavMoveRequestResolveWithLastItem(result);
12352
0
        else if (g.NavId == id)
12353
0
            g.NavTabbingCounter = 1;
12354
0
    }
12355
0
    else if (g.NavTabbingDir == -1)
12356
0
    {
12357
        // Tab Backward
12358
0
        if (g.NavId == id)
12359
0
        {
12360
0
            if (result->ID)
12361
0
            {
12362
0
                g.NavMoveScoringItems = false;
12363
0
                NavUpdateAnyRequestFlag();
12364
0
            }
12365
0
        }
12366
0
        else if (can_stop)
12367
0
        {
12368
            // Keep applying until reaching NavId
12369
0
            NavApplyItemToResult(result);
12370
0
        }
12371
0
    }
12372
0
    else if (g.NavTabbingDir == 0)
12373
0
    {
12374
0
        if (can_stop && g.NavId == id)
12375
0
            NavMoveRequestResolveWithLastItem(result);
12376
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12377
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12378
0
    }
12379
0
}
12380
12381
bool ImGui::NavMoveRequestButNoResultYet()
12382
0
{
12383
0
    ImGuiContext& g = *GImGui;
12384
0
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12385
0
}
12386
12387
// FIXME: ScoringRect is not set
12388
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12389
0
{
12390
0
    ImGuiContext& g = *GImGui;
12391
0
    IM_ASSERT(g.NavWindow != NULL);
12392
12393
0
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12394
0
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12395
12396
0
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12397
0
    g.NavMoveDir = move_dir;
12398
0
    g.NavMoveDirForDebug = move_dir;
12399
0
    g.NavMoveClipDir = clip_dir;
12400
0
    g.NavMoveFlags = move_flags;
12401
0
    g.NavMoveScrollFlags = scroll_flags;
12402
0
    g.NavMoveForwardToNextFrame = false;
12403
0
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12404
0
    g.NavMoveResultLocal.Clear();
12405
0
    g.NavMoveResultLocalVisible.Clear();
12406
0
    g.NavMoveResultOther.Clear();
12407
0
    g.NavTabbingCounter = 0;
12408
0
    g.NavTabbingResultFirst.Clear();
12409
0
    NavUpdateAnyRequestFlag();
12410
0
}
12411
12412
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12413
0
{
12414
0
    ImGuiContext& g = *GImGui;
12415
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12416
0
    NavApplyItemToResult(result);
12417
0
    NavUpdateAnyRequestFlag();
12418
0
}
12419
12420
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12421
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12422
0
{
12423
0
    ImGuiContext& g = *GImGui;
12424
0
    g.NavMoveScoringItems = false;
12425
0
    g.LastItemData.ID = tree_node_data->ID;
12426
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12427
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12428
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12429
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12430
0
    NavUpdateAnyRequestFlag();
12431
0
}
12432
12433
void ImGui::NavMoveRequestCancel()
12434
0
{
12435
0
    ImGuiContext& g = *GImGui;
12436
0
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12437
0
    NavUpdateAnyRequestFlag();
12438
0
}
12439
12440
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12441
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12442
0
{
12443
0
    ImGuiContext& g = *GImGui;
12444
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12445
0
    NavMoveRequestCancel();
12446
0
    g.NavMoveForwardToNextFrame = true;
12447
0
    g.NavMoveDir = move_dir;
12448
0
    g.NavMoveClipDir = clip_dir;
12449
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12450
0
    g.NavMoveScrollFlags = scroll_flags;
12451
0
}
12452
12453
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12454
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12455
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12456
0
{
12457
0
    ImGuiContext& g = *GImGui;
12458
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12459
12460
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12461
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12462
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12463
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12464
0
}
12465
12466
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12467
// This way we could find the last focused window among our children. It would be much less confusing this way?
12468
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12469
0
{
12470
0
    ImGuiWindow* parent = nav_window;
12471
0
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12472
0
        parent = parent->ParentWindow;
12473
0
    if (parent && parent != nav_window)
12474
0
        parent->NavLastChildNavWindow = nav_window;
12475
0
}
12476
12477
// Restore the last focused child.
12478
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12479
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12480
0
{
12481
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12482
0
        return window->NavLastChildNavWindow;
12483
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12484
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12485
0
            return tab->Window;
12486
0
    return window;
12487
0
}
12488
12489
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12490
0
{
12491
0
    ImGuiContext& g = *GImGui;
12492
0
    if (layer == ImGuiNavLayer_Main)
12493
0
    {
12494
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
12495
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12496
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12497
0
        if (prev_nav_window)
12498
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12499
0
    }
12500
0
    ImGuiWindow* window = g.NavWindow;
12501
0
    if (window->NavLastIds[layer] != 0)
12502
0
    {
12503
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12504
0
    }
12505
0
    else
12506
0
    {
12507
0
        g.NavLayer = layer;
12508
0
        NavInitWindow(window, true);
12509
0
    }
12510
0
}
12511
12512
void ImGui::NavRestoreHighlightAfterMove()
12513
0
{
12514
0
    ImGuiContext& g = *GImGui;
12515
0
    g.NavDisableHighlight = false;
12516
0
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12517
0
}
12518
12519
static inline void ImGui::NavUpdateAnyRequestFlag()
12520
0
{
12521
0
    ImGuiContext& g = *GImGui;
12522
0
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12523
0
    if (g.NavAnyRequest)
12524
0
        IM_ASSERT(g.NavWindow != NULL);
12525
0
}
12526
12527
// This needs to be called before we submit any widget (aka in or before Begin)
12528
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12529
0
{
12530
    // FIXME: ChildWindow test here is wrong for docking
12531
0
    ImGuiContext& g = *GImGui;
12532
0
    IM_ASSERT(window == g.NavWindow);
12533
12534
0
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12535
0
    {
12536
0
        g.NavId = 0;
12537
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12538
0
        return;
12539
0
    }
12540
12541
0
    bool init_for_nav = false;
12542
0
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12543
0
        init_for_nav = true;
12544
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12545
0
    if (init_for_nav)
12546
0
    {
12547
0
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12548
0
        g.NavInitRequest = true;
12549
0
        g.NavInitRequestFromMove = false;
12550
0
        g.NavInitResult.ID = 0;
12551
0
        NavUpdateAnyRequestFlag();
12552
0
    }
12553
0
    else
12554
0
    {
12555
0
        g.NavId = window->NavLastIds[0];
12556
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12557
0
    }
12558
0
}
12559
12560
static ImVec2 ImGui::NavCalcPreferredRefPos()
12561
0
{
12562
0
    ImGuiContext& g = *GImGui;
12563
0
    ImGuiWindow* window = g.NavWindow;
12564
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12565
0
    {
12566
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12567
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12568
        // In theory we could move that +1.0f offset in OpenPopupEx()
12569
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12570
0
        return ImVec2(p.x + 1.0f, p.y);
12571
0
    }
12572
0
    else
12573
0
    {
12574
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12575
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12576
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12577
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12578
0
        {
12579
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12580
0
            rect_rel.Translate(window->Scroll - next_scroll);
12581
0
        }
12582
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12583
0
        ImGuiViewport* viewport = window->Viewport;
12584
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12585
0
    }
12586
0
}
12587
12588
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12589
0
{
12590
0
    ImGuiContext& g = *GImGui;
12591
0
    float repeat_delay, repeat_rate;
12592
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12593
12594
0
    ImGuiKey key_less, key_more;
12595
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12596
0
    {
12597
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12598
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12599
0
    }
12600
0
    else
12601
0
    {
12602
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12603
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12604
0
    }
12605
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12606
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12607
0
        amount = 0.0f;
12608
0
    return amount;
12609
0
}
12610
12611
static void ImGui::NavUpdate()
12612
0
{
12613
0
    ImGuiContext& g = *GImGui;
12614
0
    ImGuiIO& io = g.IO;
12615
12616
0
    io.WantSetMousePos = false;
12617
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12618
12619
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12620
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12621
0
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12622
0
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12623
0
    if (nav_gamepad_active)
12624
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12625
0
            if (IsKeyDown(key))
12626
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12627
0
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12628
0
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12629
0
    if (nav_keyboard_active)
12630
0
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12631
0
            if (IsKeyDown(key))
12632
0
                g.NavInputSource = ImGuiInputSource_Keyboard;
12633
12634
    // Process navigation init request (select first/default focus)
12635
0
    g.NavJustMovedToId = 0;
12636
0
    if (g.NavInitResult.ID != 0)
12637
0
        NavInitRequestApplyResult();
12638
0
    g.NavInitRequest = false;
12639
0
    g.NavInitRequestFromMove = false;
12640
0
    g.NavInitResult.ID = 0;
12641
12642
    // Process navigation move request
12643
0
    if (g.NavMoveSubmitted)
12644
0
        NavMoveRequestApplyResult();
12645
0
    g.NavTabbingCounter = 0;
12646
0
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12647
12648
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12649
0
    bool set_mouse_pos = false;
12650
0
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12651
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12652
0
            set_mouse_pos = true;
12653
0
    g.NavMousePosDirty = false;
12654
0
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12655
12656
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12657
0
    if (g.NavWindow)
12658
0
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12659
0
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12660
0
        g.NavWindow->NavLastChildNavWindow = NULL;
12661
12662
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12663
0
    NavUpdateWindowing();
12664
12665
    // Set output flags for user application
12666
0
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12667
0
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12668
12669
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12670
0
    NavUpdateCancelRequest();
12671
12672
    // Process manual activation request
12673
0
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12674
0
    g.NavActivateFlags = ImGuiActivateFlags_None;
12675
0
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12676
0
    {
12677
0
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None));
12678
0
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, ImGuiKeyOwner_None)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_None)));
12679
0
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None));
12680
0
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, ImGuiKeyOwner_None) || IsKeyPressed(ImGuiKey_KeypadEnter, ImGuiKeyOwner_None))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_None)));
12681
0
        if (g.ActiveId == 0 && activate_pressed)
12682
0
        {
12683
0
            g.NavActivateId = g.NavId;
12684
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12685
0
        }
12686
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12687
0
        {
12688
0
            g.NavActivateId = g.NavId;
12689
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12690
0
        }
12691
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12692
0
            g.NavActivateDownId = g.NavId;
12693
0
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12694
0
        {
12695
0
            g.NavActivatePressedId = g.NavId;
12696
0
            NavHighlightActivated(g.NavId);
12697
0
        }
12698
0
    }
12699
0
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12700
0
        g.NavDisableHighlight = true;
12701
0
    if (g.NavActivateId != 0)
12702
0
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12703
12704
    // Highlight
12705
0
    if (g.NavHighlightActivatedTimer > 0.0f)
12706
0
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
12707
0
    if (g.NavHighlightActivatedTimer == 0.0f)
12708
0
        g.NavHighlightActivatedId = 0;
12709
12710
    // Process programmatic activation request
12711
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12712
0
    if (g.NavNextActivateId != 0)
12713
0
    {
12714
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12715
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12716
0
    }
12717
0
    g.NavNextActivateId = 0;
12718
12719
    // Process move requests
12720
0
    NavUpdateCreateMoveRequest();
12721
0
    if (g.NavMoveDir == ImGuiDir_None)
12722
0
        NavUpdateCreateTabbingRequest();
12723
0
    NavUpdateAnyRequestFlag();
12724
0
    g.NavIdIsAlive = false;
12725
12726
    // Scrolling
12727
0
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12728
0
    {
12729
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12730
0
        ImGuiWindow* window = g.NavWindow;
12731
0
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12732
0
        const ImGuiDir move_dir = g.NavMoveDir;
12733
0
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12734
0
        {
12735
0
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12736
0
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12737
0
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12738
0
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12739
0
        }
12740
12741
        // *Normal* Manual scroll with LStick
12742
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12743
0
        if (nav_gamepad_active)
12744
0
        {
12745
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12746
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12747
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12748
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12749
0
            if (scroll_dir.y != 0.0f)
12750
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12751
0
        }
12752
0
    }
12753
12754
    // Always prioritize mouse highlight if navigation is disabled
12755
0
    if (!nav_keyboard_active && !nav_gamepad_active)
12756
0
    {
12757
0
        g.NavDisableHighlight = true;
12758
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12759
0
    }
12760
12761
    // Update mouse position if requested
12762
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12763
0
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12764
0
        TeleportMousePos(NavCalcPreferredRefPos());
12765
12766
    // [DEBUG]
12767
0
    g.NavScoringDebugCount = 0;
12768
#if IMGUI_DEBUG_NAV_RECTS
12769
    if (ImGuiWindow* debug_window = g.NavWindow)
12770
    {
12771
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12772
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12773
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12774
    }
12775
#endif
12776
0
}
12777
12778
void ImGui::NavInitRequestApplyResult()
12779
0
{
12780
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12781
0
    ImGuiContext& g = *GImGui;
12782
0
    if (!g.NavWindow)
12783
0
        return;
12784
12785
0
    ImGuiNavItemData* result = &g.NavInitResult;
12786
0
    if (g.NavId != result->ID)
12787
0
    {
12788
0
        g.NavJustMovedToId = result->ID;
12789
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12790
0
        g.NavJustMovedToKeyMods = 0;
12791
0
    }
12792
12793
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12794
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12795
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12796
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12797
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12798
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12799
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12800
0
    if (g.NavInitRequestFromMove)
12801
0
        NavRestoreHighlightAfterMove();
12802
0
}
12803
12804
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12805
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12806
0
{
12807
    // Bias initial rect
12808
0
    ImGuiContext& g = *GImGui;
12809
0
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12810
12811
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12812
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12813
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12814
0
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12815
0
    {
12816
0
        if (preferred_pos_rel.x == FLT_MAX)
12817
0
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12818
0
        if (preferred_pos_rel.y == FLT_MAX)
12819
0
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12820
0
    }
12821
12822
    // Apply general bias on the other axis
12823
0
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12824
0
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12825
0
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12826
0
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12827
0
}
12828
12829
void ImGui::NavUpdateCreateMoveRequest()
12830
0
{
12831
0
    ImGuiContext& g = *GImGui;
12832
0
    ImGuiIO& io = g.IO;
12833
0
    ImGuiWindow* window = g.NavWindow;
12834
0
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12835
0
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12836
12837
0
    if (g.NavMoveForwardToNextFrame && window != NULL)
12838
0
    {
12839
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12840
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12841
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12842
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12843
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12844
0
    }
12845
0
    else
12846
0
    {
12847
        // Initiate directional inputs request
12848
0
        g.NavMoveDir = ImGuiDir_None;
12849
0
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12850
0
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12851
0
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12852
0
        {
12853
0
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | ImGuiInputFlags_RepeatRateNavMove;
12854
0
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12855
0
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12856
0
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12857
0
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12858
0
        }
12859
0
        g.NavMoveClipDir = g.NavMoveDir;
12860
0
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12861
0
    }
12862
12863
    // Update PageUp/PageDown/Home/End scroll
12864
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12865
0
    float scoring_rect_offset_y = 0.0f;
12866
0
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12867
0
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12868
0
    if (scoring_rect_offset_y != 0.0f)
12869
0
    {
12870
0
        g.NavScoringNoClipRect = window->InnerRect;
12871
0
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12872
0
    }
12873
12874
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12875
#if IMGUI_DEBUG_NAV_SCORING
12876
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12877
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12878
    if (io.KeyCtrl)
12879
    {
12880
        if (g.NavMoveDir == ImGuiDir_None)
12881
            g.NavMoveDir = g.NavMoveDirForDebug;
12882
        g.NavMoveClipDir = g.NavMoveDir;
12883
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12884
    }
12885
#endif
12886
12887
    // Submit
12888
0
    g.NavMoveForwardToNextFrame = false;
12889
0
    if (g.NavMoveDir != ImGuiDir_None)
12890
0
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12891
12892
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12893
0
    if (g.NavMoveSubmitted && g.NavId == 0)
12894
0
    {
12895
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12896
0
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12897
0
        g.NavInitResult.ID = 0;
12898
0
        g.NavDisableHighlight = false;
12899
0
    }
12900
12901
    // When using gamepad, we project the reference nav bounding box into window visible area.
12902
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12903
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12904
0
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12905
0
    {
12906
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12907
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12908
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12909
12910
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12911
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12912
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12913
12914
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12915
0
        {
12916
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12917
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12918
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12919
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12920
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12921
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12922
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12923
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12924
0
            g.NavId = 0;
12925
0
        }
12926
0
    }
12927
12928
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12929
0
    ImRect scoring_rect;
12930
0
    if (window != NULL)
12931
0
    {
12932
0
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12933
0
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12934
0
        scoring_rect.TranslateY(scoring_rect_offset_y);
12935
0
        if (g.NavMoveSubmitted)
12936
0
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12937
0
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12938
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12939
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12940
0
    }
12941
0
    g.NavScoringRect = scoring_rect;
12942
0
    g.NavScoringNoClipRect.Add(scoring_rect);
12943
0
}
12944
12945
void ImGui::NavUpdateCreateTabbingRequest()
12946
0
{
12947
0
    ImGuiContext& g = *GImGui;
12948
0
    ImGuiWindow* window = g.NavWindow;
12949
0
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12950
0
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12951
0
        return;
12952
12953
0
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12954
0
    if (!tab_pressed)
12955
0
        return;
12956
12957
    // Initiate tabbing request
12958
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12959
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12960
0
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12961
0
    if (nav_keyboard_active)
12962
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12963
0
    else
12964
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12965
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12966
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12967
0
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12968
0
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12969
0
    g.NavTabbingCounter = -1;
12970
0
}
12971
12972
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12973
void ImGui::NavMoveRequestApplyResult()
12974
0
{
12975
0
    ImGuiContext& g = *GImGui;
12976
#if IMGUI_DEBUG_NAV_SCORING
12977
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12978
        return;
12979
#endif
12980
12981
    // Select which result to use
12982
0
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12983
12984
    // Tabbing forward wrap
12985
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12986
0
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12987
0
            result = &g.NavTabbingResultFirst;
12988
12989
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12990
0
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12991
0
    if (result == NULL)
12992
0
    {
12993
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12994
0
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12995
0
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12996
0
            NavRestoreHighlightAfterMove();
12997
0
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12998
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12999
0
        return;
13000
0
    }
13001
13002
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13003
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13004
0
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13005
0
            result = &g.NavMoveResultLocalVisible;
13006
13007
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13008
0
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13009
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13010
0
            result = &g.NavMoveResultOther;
13011
0
    IM_ASSERT(g.NavWindow && result->Window);
13012
13013
    // Scroll to keep newly navigated item fully into view.
13014
0
    if (g.NavLayer == ImGuiNavLayer_Main)
13015
0
    {
13016
0
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13017
0
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13018
13019
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13020
0
        {
13021
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13022
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13023
0
            SetScrollY(result->Window, scroll_target);
13024
0
        }
13025
0
    }
13026
13027
0
    if (g.NavWindow != result->Window)
13028
0
    {
13029
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13030
0
        g.NavWindow = result->Window;
13031
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13032
0
    }
13033
13034
    // Clear active id unless requested not to
13035
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13036
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13037
0
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13038
0
        ClearActiveID();
13039
13040
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13041
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13042
0
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13043
0
    {
13044
0
        g.NavJustMovedToId = result->ID;
13045
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13046
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13047
0
    }
13048
13049
    // Apply new NavID/Focus
13050
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13051
0
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13052
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13053
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13054
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13055
13056
    // Restore last preferred position for current axis
13057
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13058
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13059
0
    {
13060
0
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13061
0
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13062
0
    }
13063
13064
    // Tabbing: Activates Inputable, otherwise only Focus
13065
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13066
0
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13067
13068
    // Activate
13069
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13070
0
    {
13071
0
        g.NavNextActivateId = result->ID;
13072
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13073
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13074
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13075
0
    }
13076
13077
    // Enable nav highlight
13078
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13079
0
        NavRestoreHighlightAfterMove();
13080
0
}
13081
13082
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13083
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13084
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13085
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13086
static void ImGui::NavUpdateCancelRequest()
13087
0
{
13088
0
    ImGuiContext& g = *GImGui;
13089
0
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13090
0
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13091
0
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
13092
0
        return;
13093
13094
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13095
0
    if (g.ActiveId != 0)
13096
0
    {
13097
0
        ClearActiveID();
13098
0
    }
13099
0
    else if (g.NavLayer != ImGuiNavLayer_Main)
13100
0
    {
13101
        // Leave the "menu" layer
13102
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13103
0
        NavRestoreHighlightAfterMove();
13104
0
    }
13105
0
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13106
0
    {
13107
        // Exit child window
13108
0
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13109
0
        ImGuiWindow* parent_window = child_window->ParentWindow;
13110
0
        IM_ASSERT(child_window->ChildId != 0);
13111
0
        FocusWindow(parent_window);
13112
0
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13113
0
        NavRestoreHighlightAfterMove();
13114
0
    }
13115
0
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13116
0
    {
13117
        // Close open popup/menu
13118
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13119
0
    }
13120
0
    else
13121
0
    {
13122
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13123
0
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13124
0
            g.NavWindow->NavLastIds[0] = 0;
13125
0
        g.NavId = 0;
13126
0
    }
13127
0
}
13128
13129
// Handle PageUp/PageDown/Home/End keys
13130
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13131
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13132
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13133
static float ImGui::NavUpdatePageUpPageDown()
13134
0
{
13135
0
    ImGuiContext& g = *GImGui;
13136
0
    ImGuiWindow* window = g.NavWindow;
13137
0
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13138
0
        return 0.0f;
13139
13140
0
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
13141
0
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
13142
0
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
13143
0
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
13144
0
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13145
0
        return 0.0f;
13146
13147
0
    if (g.NavLayer != ImGuiNavLayer_Main)
13148
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13149
13150
0
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13151
0
    {
13152
        // Fallback manual-scroll when window has no navigable item
13153
0
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
13154
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13155
0
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
13156
0
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13157
0
        else if (home_pressed)
13158
0
            SetScrollY(window, 0.0f);
13159
0
        else if (end_pressed)
13160
0
            SetScrollY(window, window->ScrollMax.y);
13161
0
    }
13162
0
    else
13163
0
    {
13164
0
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13165
0
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13166
0
        float nav_scoring_rect_offset_y = 0.0f;
13167
0
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13168
0
        {
13169
0
            nav_scoring_rect_offset_y = -page_offset_y;
13170
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13171
0
            g.NavMoveClipDir = ImGuiDir_Up;
13172
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13173
0
        }
13174
0
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13175
0
        {
13176
0
            nav_scoring_rect_offset_y = +page_offset_y;
13177
0
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13178
0
            g.NavMoveClipDir = ImGuiDir_Down;
13179
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13180
0
        }
13181
0
        else if (home_pressed)
13182
0
        {
13183
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13184
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13185
            // Preserve current horizontal position if we have any.
13186
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13187
0
            if (nav_rect_rel.IsInverted())
13188
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13189
0
            g.NavMoveDir = ImGuiDir_Down;
13190
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13191
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13192
0
        }
13193
0
        else if (end_pressed)
13194
0
        {
13195
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13196
0
            if (nav_rect_rel.IsInverted())
13197
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13198
0
            g.NavMoveDir = ImGuiDir_Up;
13199
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13200
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13201
0
        }
13202
0
        return nav_scoring_rect_offset_y;
13203
0
    }
13204
0
    return 0.0f;
13205
0
}
13206
13207
static void ImGui::NavEndFrame()
13208
0
{
13209
0
    ImGuiContext& g = *GImGui;
13210
13211
    // Show CTRL+TAB list window
13212
0
    if (g.NavWindowingTarget != NULL)
13213
0
        NavUpdateWindowingOverlay();
13214
13215
    // Perform wrap-around in menus
13216
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13217
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13218
0
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13219
0
        NavUpdateCreateWrappingRequest();
13220
0
}
13221
13222
static void ImGui::NavUpdateCreateWrappingRequest()
13223
0
{
13224
0
    ImGuiContext& g = *GImGui;
13225
0
    ImGuiWindow* window = g.NavWindow;
13226
13227
0
    bool do_forward = false;
13228
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13229
0
    ImGuiDir clip_dir = g.NavMoveDir;
13230
13231
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13232
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13233
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13234
0
    {
13235
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13236
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13237
0
        {
13238
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13239
0
            clip_dir = ImGuiDir_Up;
13240
0
        }
13241
0
        do_forward = true;
13242
0
    }
13243
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13244
0
    {
13245
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13246
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13247
0
        {
13248
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13249
0
            clip_dir = ImGuiDir_Down;
13250
0
        }
13251
0
        do_forward = true;
13252
0
    }
13253
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13254
0
    {
13255
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13256
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13257
0
        {
13258
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13259
0
            clip_dir = ImGuiDir_Left;
13260
0
        }
13261
0
        do_forward = true;
13262
0
    }
13263
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13264
0
    {
13265
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13266
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13267
0
        {
13268
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13269
0
            clip_dir = ImGuiDir_Right;
13270
0
        }
13271
0
        do_forward = true;
13272
0
    }
13273
0
    if (!do_forward)
13274
0
        return;
13275
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13276
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13277
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13278
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13279
0
}
13280
13281
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13282
0
{
13283
0
    ImGuiContext& g = *GImGui;
13284
0
    IM_UNUSED(g);
13285
0
    int order = window->FocusOrder;
13286
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13287
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13288
0
    return order;
13289
0
}
13290
13291
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13292
0
{
13293
0
    ImGuiContext& g = *GImGui;
13294
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13295
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13296
0
            return g.WindowsFocusOrder[i];
13297
0
    return NULL;
13298
0
}
13299
13300
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13301
0
{
13302
0
    ImGuiContext& g = *GImGui;
13303
0
    IM_ASSERT(g.NavWindowingTarget);
13304
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13305
0
        return;
13306
13307
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13308
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13309
0
    if (!window_target)
13310
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13311
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13312
0
    {
13313
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13314
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13315
0
    }
13316
0
    g.NavWindowingToggleLayer = false;
13317
0
}
13318
13319
// Windowing management mode
13320
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13321
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13322
static void ImGui::NavUpdateWindowing()
13323
0
{
13324
0
    ImGuiContext& g = *GImGui;
13325
0
    ImGuiIO& io = g.IO;
13326
13327
0
    ImGuiWindow* apply_focus_window = NULL;
13328
0
    bool apply_toggle_layer = false;
13329
13330
0
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13331
0
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13332
0
    if (!allow_windowing)
13333
0
        g.NavWindowingTarget = NULL;
13334
13335
    // Fade out
13336
0
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13337
0
    {
13338
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13339
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13340
0
            g.NavWindowingTargetAnim = NULL;
13341
0
    }
13342
13343
    // Start CTRL+Tab or Square+L/R window selection
13344
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13345
0
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13346
0
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13347
0
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13348
0
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13349
0
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
13350
0
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
13351
0
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13352
0
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13353
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13354
0
        {
13355
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13356
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13357
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13358
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13359
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13360
13361
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
13362
0
            if (keyboard_next_window || keyboard_prev_window)
13363
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13364
0
        }
13365
13366
    // Gamepad update
13367
0
    g.NavWindowingTimer += io.DeltaTime;
13368
0
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13369
0
    {
13370
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13371
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13372
13373
        // Select window to focus
13374
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13375
0
        if (focus_change_dir != 0)
13376
0
        {
13377
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13378
0
            g.NavWindowingHighlightAlpha = 1.0f;
13379
0
        }
13380
13381
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13382
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13383
0
        {
13384
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13385
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13386
0
                apply_toggle_layer = true;
13387
0
            else if (!g.NavWindowingToggleLayer)
13388
0
                apply_focus_window = g.NavWindowingTarget;
13389
0
            g.NavWindowingTarget = NULL;
13390
0
        }
13391
0
    }
13392
13393
    // Keyboard: Focus
13394
0
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13395
0
    {
13396
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13397
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13398
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13399
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13400
0
        if (keyboard_next_window || keyboard_prev_window)
13401
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13402
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13403
0
            apply_focus_window = g.NavWindowingTarget;
13404
0
    }
13405
13406
    // Keyboard: Press and Release ALT to toggle menu layer
13407
0
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13408
0
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13409
0
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, ImGuiKeyOwner_None))
13410
0
        {
13411
0
            g.NavWindowingToggleLayer = true;
13412
0
            g.NavWindowingToggleKey = windowing_toggle_key;
13413
0
            g.NavInputSource = ImGuiInputSource_Keyboard;
13414
0
            break;
13415
0
        }
13416
0
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13417
0
    {
13418
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13419
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13420
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13421
        // We cancel toggling nav layer if an owner has claimed the key.
13422
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13423
0
            g.NavWindowingToggleLayer = false;
13424
0
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_None) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13425
0
            g.NavWindowingToggleLayer = false;
13426
13427
        // Apply layer toggle on Alt release
13428
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13429
0
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13430
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13431
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13432
0
                    apply_toggle_layer = true;
13433
0
        if (!IsKeyDown(g.NavWindowingToggleKey))
13434
0
            g.NavWindowingToggleLayer = false;
13435
0
    }
13436
13437
    // Move window
13438
0
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13439
0
    {
13440
0
        ImVec2 nav_move_dir;
13441
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13442
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13443
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13444
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13445
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13446
0
        {
13447
0
            const float NAV_MOVE_SPEED = 800.0f;
13448
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13449
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13450
0
            g.NavDisableMouseHover = true;
13451
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13452
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13453
0
            {
13454
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13455
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13456
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13457
0
            }
13458
0
        }
13459
0
    }
13460
13461
    // Apply final focus
13462
0
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13463
0
    {
13464
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13465
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13466
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13467
0
        ClearActiveID();
13468
0
        NavRestoreHighlightAfterMove();
13469
0
        ClosePopupsOverWindow(apply_focus_window, false);
13470
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13471
0
        apply_focus_window = g.NavWindow;
13472
0
        if (apply_focus_window->NavLastIds[0] == 0)
13473
0
            NavInitWindow(apply_focus_window, false);
13474
13475
        // If the window has ONLY a menu layer (no main layer), select it directly
13476
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13477
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13478
        // the target window as already been previewed once.
13479
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13480
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13481
        // won't be valid.
13482
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13483
0
            g.NavLayer = ImGuiNavLayer_Menu;
13484
13485
        // Request OS level focus
13486
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13487
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13488
0
    }
13489
0
    if (apply_focus_window)
13490
0
        g.NavWindowingTarget = NULL;
13491
13492
    // Apply menu/layer toggle
13493
0
    if (apply_toggle_layer && g.NavWindow)
13494
0
    {
13495
0
        ClearActiveID();
13496
13497
        // Move to parent menu if necessary
13498
0
        ImGuiWindow* new_nav_window = g.NavWindow;
13499
0
        while (new_nav_window->ParentWindow
13500
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13501
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13502
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13503
0
            new_nav_window = new_nav_window->ParentWindow;
13504
0
        if (new_nav_window != g.NavWindow)
13505
0
        {
13506
0
            ImGuiWindow* old_nav_window = g.NavWindow;
13507
0
            FocusWindow(new_nav_window);
13508
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13509
0
        }
13510
13511
        // Toggle layer
13512
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13513
0
        if (new_nav_layer != g.NavLayer)
13514
0
        {
13515
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13516
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13517
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13518
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13519
0
            NavRestoreLayer(new_nav_layer);
13520
0
            NavRestoreHighlightAfterMove();
13521
0
        }
13522
0
    }
13523
0
}
13524
13525
// Window has already passed the IsWindowNavFocusable()
13526
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13527
0
{
13528
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13529
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13530
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13531
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13532
0
    if (window->DockNodeAsHost)
13533
0
        return "(Dock node)"; // Not normally shown to user.
13534
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13535
0
}
13536
13537
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13538
void ImGui::NavUpdateWindowingOverlay()
13539
0
{
13540
0
    ImGuiContext& g = *GImGui;
13541
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13542
13543
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13544
0
        return;
13545
13546
0
    if (g.NavWindowingListWindow == NULL)
13547
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13548
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13549
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13550
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13551
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13552
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13553
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13554
0
    {
13555
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13556
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13557
0
        if (!IsWindowNavFocusable(window))
13558
0
            continue;
13559
0
        const char* label = window->Name;
13560
0
        if (label == FindRenderedTextEnd(label))
13561
0
            label = GetFallbackWindowNameForWindowingList(window);
13562
0
        Selectable(label, g.NavWindowingTarget == window);
13563
0
    }
13564
0
    End();
13565
0
    PopStyleVar();
13566
0
}
13567
13568
13569
//-----------------------------------------------------------------------------
13570
// [SECTION] DRAG AND DROP
13571
//-----------------------------------------------------------------------------
13572
13573
bool ImGui::IsDragDropActive()
13574
0
{
13575
0
    ImGuiContext& g = *GImGui;
13576
0
    return g.DragDropActive;
13577
0
}
13578
13579
void ImGui::ClearDragDrop()
13580
0
{
13581
0
    ImGuiContext& g = *GImGui;
13582
0
    g.DragDropActive = false;
13583
0
    g.DragDropPayload.Clear();
13584
0
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13585
0
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13586
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13587
0
    g.DragDropAcceptFrameCount = -1;
13588
13589
0
    g.DragDropPayloadBufHeap.clear();
13590
0
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13591
0
}
13592
13593
bool ImGui::BeginTooltipHidden()
13594
0
{
13595
0
    ImGuiContext& g = *GImGui;
13596
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13597
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13598
0
    return ret;
13599
0
}
13600
13601
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13602
// If the item has an identifier:
13603
// - This assume/require the item to be activated (typically via ButtonBehavior).
13604
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13605
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13606
// If the item has no identifier:
13607
// - Currently always assume left mouse button.
13608
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13609
0
{
13610
0
    ImGuiContext& g = *GImGui;
13611
0
    ImGuiWindow* window = g.CurrentWindow;
13612
13613
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13614
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13615
0
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13616
13617
0
    bool source_drag_active = false;
13618
0
    ImGuiID source_id = 0;
13619
0
    ImGuiID source_parent_id = 0;
13620
0
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13621
0
    {
13622
0
        source_id = g.LastItemData.ID;
13623
0
        if (source_id != 0)
13624
0
        {
13625
            // Common path: items with ID
13626
0
            if (g.ActiveId != source_id)
13627
0
                return false;
13628
0
            if (g.ActiveIdMouseButton != -1)
13629
0
                mouse_button = g.ActiveIdMouseButton;
13630
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13631
0
                return false;
13632
0
            g.ActiveIdAllowOverlap = false;
13633
0
        }
13634
0
        else
13635
0
        {
13636
            // Uncommon path: items without ID
13637
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13638
0
                return false;
13639
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13640
0
                return false;
13641
13642
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13643
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13644
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13645
0
            {
13646
0
                IM_ASSERT(0);
13647
0
                return false;
13648
0
            }
13649
13650
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13651
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13652
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13653
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13654
            // Rely on keeping other window->LastItemXXX fields intact.
13655
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13656
0
            KeepAliveID(source_id);
13657
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13658
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13659
0
            {
13660
0
                SetActiveID(source_id, window);
13661
0
                FocusWindow(window);
13662
0
            }
13663
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13664
0
                g.ActiveIdAllowOverlap = is_hovered;
13665
0
        }
13666
0
        if (g.ActiveId != source_id)
13667
0
            return false;
13668
0
        source_parent_id = window->IDStack.back();
13669
0
        source_drag_active = IsMouseDragging(mouse_button);
13670
13671
        // Disable navigation and key inputs while dragging + cancel existing request if any
13672
0
        SetActiveIdUsingAllKeyboardKeys();
13673
0
    }
13674
0
    else
13675
0
    {
13676
0
        window = NULL;
13677
0
        source_id = ImHashStr("#SourceExtern");
13678
0
        source_drag_active = true;
13679
0
    }
13680
13681
0
    IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13682
0
    if (source_drag_active)
13683
0
    {
13684
0
        if (!g.DragDropActive)
13685
0
        {
13686
0
            IM_ASSERT(source_id != 0);
13687
0
            ClearDragDrop();
13688
0
            ImGuiPayload& payload = g.DragDropPayload;
13689
0
            payload.SourceId = source_id;
13690
0
            payload.SourceParentId = source_parent_id;
13691
0
            g.DragDropActive = true;
13692
0
            g.DragDropSourceFlags = flags;
13693
0
            g.DragDropMouseButton = mouse_button;
13694
0
            if (payload.SourceId == g.ActiveId)
13695
0
                g.ActiveIdNoClearOnFocusLoss = true;
13696
0
        }
13697
0
        g.DragDropSourceFrameCount = g.FrameCount;
13698
0
        g.DragDropWithinSource = true;
13699
13700
0
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13701
0
        {
13702
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13703
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13704
0
            bool ret;
13705
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13706
0
                ret = BeginTooltipHidden();
13707
0
            else
13708
0
                ret = BeginTooltip();
13709
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13710
0
            IM_UNUSED(ret);
13711
0
        }
13712
13713
0
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13714
0
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13715
13716
0
        return true;
13717
0
    }
13718
0
    return false;
13719
0
}
13720
13721
void ImGui::EndDragDropSource()
13722
0
{
13723
0
    ImGuiContext& g = *GImGui;
13724
0
    IM_ASSERT(g.DragDropActive);
13725
0
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13726
13727
0
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13728
0
        EndTooltip();
13729
13730
    // Discard the drag if have not called SetDragDropPayload()
13731
0
    if (g.DragDropPayload.DataFrameCount == -1)
13732
0
        ClearDragDrop();
13733
0
    g.DragDropWithinSource = false;
13734
0
}
13735
13736
// Use 'cond' to choose to submit payload on drag start or every frame
13737
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13738
0
{
13739
0
    ImGuiContext& g = *GImGui;
13740
0
    ImGuiPayload& payload = g.DragDropPayload;
13741
0
    if (cond == 0)
13742
0
        cond = ImGuiCond_Always;
13743
13744
0
    IM_ASSERT(type != NULL);
13745
0
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13746
0
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13747
0
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13748
0
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13749
13750
0
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13751
0
    {
13752
        // Copy payload
13753
0
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13754
0
        g.DragDropPayloadBufHeap.resize(0);
13755
0
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13756
0
        {
13757
            // Store in heap
13758
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13759
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13760
0
            memcpy(payload.Data, data, data_size);
13761
0
        }
13762
0
        else if (data_size > 0)
13763
0
        {
13764
            // Store locally
13765
0
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13766
0
            payload.Data = g.DragDropPayloadBufLocal;
13767
0
            memcpy(payload.Data, data, data_size);
13768
0
        }
13769
0
        else
13770
0
        {
13771
0
            payload.Data = NULL;
13772
0
        }
13773
0
        payload.DataSize = (int)data_size;
13774
0
    }
13775
0
    payload.DataFrameCount = g.FrameCount;
13776
13777
    // Return whether the payload has been accepted
13778
0
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13779
0
}
13780
13781
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13782
0
{
13783
0
    ImGuiContext& g = *GImGui;
13784
0
    if (!g.DragDropActive)
13785
0
        return false;
13786
13787
0
    ImGuiWindow* window = g.CurrentWindow;
13788
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13789
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13790
0
        return false;
13791
0
    IM_ASSERT(id != 0);
13792
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13793
0
        return false;
13794
0
    if (window->SkipItems)
13795
0
        return false;
13796
13797
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13798
0
    g.DragDropTargetRect = bb;
13799
0
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overriden by user depending on use case?
13800
0
    g.DragDropTargetId = id;
13801
0
    g.DragDropWithinTarget = true;
13802
0
    return true;
13803
0
}
13804
13805
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13806
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13807
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13808
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13809
bool ImGui::BeginDragDropTarget()
13810
0
{
13811
0
    ImGuiContext& g = *GImGui;
13812
0
    if (!g.DragDropActive)
13813
0
        return false;
13814
13815
0
    ImGuiWindow* window = g.CurrentWindow;
13816
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13817
0
        return false;
13818
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13819
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13820
0
        return false;
13821
13822
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13823
0
    ImGuiID id = g.LastItemData.ID;
13824
0
    if (id == 0)
13825
0
    {
13826
0
        id = window->GetIDFromRectangle(display_rect);
13827
0
        KeepAliveID(id);
13828
0
    }
13829
0
    if (g.DragDropPayload.SourceId == id)
13830
0
        return false;
13831
13832
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
13833
0
    g.DragDropTargetRect = display_rect;
13834
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
13835
0
    g.DragDropTargetId = id;
13836
0
    g.DragDropWithinTarget = true;
13837
0
    return true;
13838
0
}
13839
13840
bool ImGui::IsDragDropPayloadBeingAccepted()
13841
0
{
13842
0
    ImGuiContext& g = *GImGui;
13843
0
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13844
0
}
13845
13846
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13847
0
{
13848
0
    ImGuiContext& g = *GImGui;
13849
0
    ImGuiPayload& payload = g.DragDropPayload;
13850
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13851
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13852
0
    if (type != NULL && !payload.IsDataType(type))
13853
0
        return NULL;
13854
13855
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13856
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13857
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13858
0
    ImRect r = g.DragDropTargetRect;
13859
0
    float r_surface = r.GetWidth() * r.GetHeight();
13860
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13861
0
        return NULL;
13862
13863
0
    g.DragDropAcceptFlags = flags;
13864
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13865
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13866
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13867
13868
    // Render default drop visuals
13869
0
    payload.Preview = was_accepted_previously;
13870
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13871
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13872
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
13873
13874
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13875
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13876
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13877
0
        return NULL;
13878
13879
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13880
0
    return &payload;
13881
0
}
13882
13883
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13884
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
13885
0
{
13886
0
    ImGuiContext& g = *GImGui;
13887
0
    ImGuiWindow* window = g.CurrentWindow;
13888
0
    ImRect bb_display = bb;
13889
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13890
0
    bb_display.Expand(3.5f);
13891
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
13892
0
    if (push_clip_rect)
13893
0
        window->DrawList->PushClipRectFullScreen();
13894
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13895
0
    if (push_clip_rect)
13896
0
        window->DrawList->PopClipRect();
13897
0
}
13898
13899
const ImGuiPayload* ImGui::GetDragDropPayload()
13900
0
{
13901
0
    ImGuiContext& g = *GImGui;
13902
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13903
0
}
13904
13905
void ImGui::EndDragDropTarget()
13906
0
{
13907
0
    ImGuiContext& g = *GImGui;
13908
0
    IM_ASSERT(g.DragDropActive);
13909
0
    IM_ASSERT(g.DragDropWithinTarget);
13910
0
    g.DragDropWithinTarget = false;
13911
13912
    // Clear drag and drop state payload right after delivery
13913
0
    if (g.DragDropPayload.Delivery)
13914
0
        ClearDragDrop();
13915
0
}
13916
13917
//-----------------------------------------------------------------------------
13918
// [SECTION] LOGGING/CAPTURING
13919
//-----------------------------------------------------------------------------
13920
// All text output from the interface can be captured into tty/file/clipboard.
13921
// By default, tree nodes are automatically opened during logging.
13922
//-----------------------------------------------------------------------------
13923
13924
// Pass text data straight to log (without being displayed)
13925
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13926
0
{
13927
0
    if (g.LogFile)
13928
0
    {
13929
0
        g.LogBuffer.Buf.resize(0);
13930
0
        g.LogBuffer.appendfv(fmt, args);
13931
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13932
0
    }
13933
0
    else
13934
0
    {
13935
0
        g.LogBuffer.appendfv(fmt, args);
13936
0
    }
13937
0
}
13938
13939
void ImGui::LogText(const char* fmt, ...)
13940
0
{
13941
0
    ImGuiContext& g = *GImGui;
13942
0
    if (!g.LogEnabled)
13943
0
        return;
13944
13945
0
    va_list args;
13946
0
    va_start(args, fmt);
13947
0
    LogTextV(g, fmt, args);
13948
0
    va_end(args);
13949
0
}
13950
13951
void ImGui::LogTextV(const char* fmt, va_list args)
13952
0
{
13953
0
    ImGuiContext& g = *GImGui;
13954
0
    if (!g.LogEnabled)
13955
0
        return;
13956
13957
0
    LogTextV(g, fmt, args);
13958
0
}
13959
13960
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13961
// We split text into individual lines to add current tree level padding
13962
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13963
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13964
0
{
13965
0
    ImGuiContext& g = *GImGui;
13966
0
    ImGuiWindow* window = g.CurrentWindow;
13967
13968
0
    const char* prefix = g.LogNextPrefix;
13969
0
    const char* suffix = g.LogNextSuffix;
13970
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13971
13972
0
    if (!text_end)
13973
0
        text_end = FindRenderedTextEnd(text, text_end);
13974
13975
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13976
0
    if (ref_pos)
13977
0
        g.LogLinePosY = ref_pos->y;
13978
0
    if (log_new_line)
13979
0
    {
13980
0
        LogText(IM_NEWLINE);
13981
0
        g.LogLineFirstItem = true;
13982
0
    }
13983
13984
0
    if (prefix)
13985
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13986
13987
    // Re-adjust padding if we have popped out of our starting depth
13988
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13989
0
        g.LogDepthRef = window->DC.TreeDepth;
13990
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13991
13992
0
    const char* text_remaining = text;
13993
0
    for (;;)
13994
0
    {
13995
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13996
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13997
0
        const char* line_start = text_remaining;
13998
0
        const char* line_end = ImStreolRange(line_start, text_end);
13999
0
        const bool is_last_line = (line_end == text_end);
14000
0
        if (line_start != line_end || !is_last_line)
14001
0
        {
14002
0
            const int line_length = (int)(line_end - line_start);
14003
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14004
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
14005
0
            g.LogLineFirstItem = false;
14006
0
            if (*line_end == '\n')
14007
0
            {
14008
0
                LogText(IM_NEWLINE);
14009
0
                g.LogLineFirstItem = true;
14010
0
            }
14011
0
        }
14012
0
        if (is_last_line)
14013
0
            break;
14014
0
        text_remaining = line_end + 1;
14015
0
    }
14016
14017
0
    if (suffix)
14018
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14019
0
}
14020
14021
// Start logging/capturing text output
14022
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
14023
0
{
14024
0
    ImGuiContext& g = *GImGui;
14025
0
    ImGuiWindow* window = g.CurrentWindow;
14026
0
    IM_ASSERT(g.LogEnabled == false);
14027
0
    IM_ASSERT(g.LogFile == NULL);
14028
0
    IM_ASSERT(g.LogBuffer.empty());
14029
0
    g.LogEnabled = true;
14030
0
    g.LogType = type;
14031
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14032
0
    g.LogDepthRef = window->DC.TreeDepth;
14033
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14034
0
    g.LogLinePosY = FLT_MAX;
14035
0
    g.LogLineFirstItem = true;
14036
0
}
14037
14038
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14039
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14040
0
{
14041
0
    ImGuiContext& g = *GImGui;
14042
0
    g.LogNextPrefix = prefix;
14043
0
    g.LogNextSuffix = suffix;
14044
0
}
14045
14046
void ImGui::LogToTTY(int auto_open_depth)
14047
0
{
14048
0
    ImGuiContext& g = *GImGui;
14049
0
    if (g.LogEnabled)
14050
0
        return;
14051
0
    IM_UNUSED(auto_open_depth);
14052
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14053
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14054
0
    g.LogFile = stdout;
14055
0
#endif
14056
0
}
14057
14058
// Start logging/capturing text output to given file
14059
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14060
0
{
14061
0
    ImGuiContext& g = *GImGui;
14062
0
    if (g.LogEnabled)
14063
0
        return;
14064
14065
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14066
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14067
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14068
0
    if (!filename)
14069
0
        filename = g.IO.LogFilename;
14070
0
    if (!filename || !filename[0])
14071
0
        return;
14072
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14073
0
    if (!f)
14074
0
    {
14075
0
        IM_ASSERT(0);
14076
0
        return;
14077
0
    }
14078
14079
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14080
0
    g.LogFile = f;
14081
0
}
14082
14083
// Start logging/capturing text output to clipboard
14084
void ImGui::LogToClipboard(int auto_open_depth)
14085
0
{
14086
0
    ImGuiContext& g = *GImGui;
14087
0
    if (g.LogEnabled)
14088
0
        return;
14089
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14090
0
}
14091
14092
void ImGui::LogToBuffer(int auto_open_depth)
14093
0
{
14094
0
    ImGuiContext& g = *GImGui;
14095
0
    if (g.LogEnabled)
14096
0
        return;
14097
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14098
0
}
14099
14100
void ImGui::LogFinish()
14101
0
{
14102
0
    ImGuiContext& g = *GImGui;
14103
0
    if (!g.LogEnabled)
14104
0
        return;
14105
14106
0
    LogText(IM_NEWLINE);
14107
0
    switch (g.LogType)
14108
0
    {
14109
0
    case ImGuiLogType_TTY:
14110
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14111
0
        fflush(g.LogFile);
14112
0
#endif
14113
0
        break;
14114
0
    case ImGuiLogType_File:
14115
0
        ImFileClose(g.LogFile);
14116
0
        break;
14117
0
    case ImGuiLogType_Buffer:
14118
0
        break;
14119
0
    case ImGuiLogType_Clipboard:
14120
0
        if (!g.LogBuffer.empty())
14121
0
            SetClipboardText(g.LogBuffer.begin());
14122
0
        break;
14123
0
    case ImGuiLogType_None:
14124
0
        IM_ASSERT(0);
14125
0
        break;
14126
0
    }
14127
14128
0
    g.LogEnabled = false;
14129
0
    g.LogType = ImGuiLogType_None;
14130
0
    g.LogFile = NULL;
14131
0
    g.LogBuffer.clear();
14132
0
}
14133
14134
// Helper to display logging buttons
14135
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14136
void ImGui::LogButtons()
14137
0
{
14138
0
    ImGuiContext& g = *GImGui;
14139
14140
0
    PushID("LogButtons");
14141
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14142
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14143
#else
14144
    const bool log_to_tty = false;
14145
#endif
14146
0
    const bool log_to_file = Button("Log To File"); SameLine();
14147
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14148
0
    PushTabStop(false);
14149
0
    SetNextItemWidth(80.0f);
14150
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14151
0
    PopTabStop();
14152
0
    PopID();
14153
14154
    // Start logging at the end of the function so that the buttons don't appear in the log
14155
0
    if (log_to_tty)
14156
0
        LogToTTY();
14157
0
    if (log_to_file)
14158
0
        LogToFile();
14159
0
    if (log_to_clipboard)
14160
0
        LogToClipboard();
14161
0
}
14162
14163
14164
//-----------------------------------------------------------------------------
14165
// [SECTION] SETTINGS
14166
//-----------------------------------------------------------------------------
14167
// - UpdateSettings() [Internal]
14168
// - MarkIniSettingsDirty() [Internal]
14169
// - FindSettingsHandler() [Internal]
14170
// - ClearIniSettings() [Internal]
14171
// - LoadIniSettingsFromDisk()
14172
// - LoadIniSettingsFromMemory()
14173
// - SaveIniSettingsToDisk()
14174
// - SaveIniSettingsToMemory()
14175
//-----------------------------------------------------------------------------
14176
// - CreateNewWindowSettings() [Internal]
14177
// - FindWindowSettingsByID() [Internal]
14178
// - FindWindowSettingsByWindow() [Internal]
14179
// - ClearWindowSettings() [Internal]
14180
// - WindowSettingsHandler_***() [Internal]
14181
//-----------------------------------------------------------------------------
14182
14183
// Called by NewFrame()
14184
void ImGui::UpdateSettings()
14185
0
{
14186
    // Load settings on first frame (if not explicitly loaded manually before)
14187
0
    ImGuiContext& g = *GImGui;
14188
0
    if (!g.SettingsLoaded)
14189
0
    {
14190
0
        IM_ASSERT(g.SettingsWindows.empty());
14191
0
        if (g.IO.IniFilename)
14192
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14193
0
        g.SettingsLoaded = true;
14194
0
    }
14195
14196
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14197
0
    if (g.SettingsDirtyTimer > 0.0f)
14198
0
    {
14199
0
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14200
0
        if (g.SettingsDirtyTimer <= 0.0f)
14201
0
        {
14202
0
            if (g.IO.IniFilename != NULL)
14203
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14204
0
            else
14205
0
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14206
0
            g.SettingsDirtyTimer = 0.0f;
14207
0
        }
14208
0
    }
14209
0
}
14210
14211
void ImGui::MarkIniSettingsDirty()
14212
0
{
14213
0
    ImGuiContext& g = *GImGui;
14214
0
    if (g.SettingsDirtyTimer <= 0.0f)
14215
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14216
0
}
14217
14218
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14219
0
{
14220
0
    ImGuiContext& g = *GImGui;
14221
0
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14222
0
        if (g.SettingsDirtyTimer <= 0.0f)
14223
0
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14224
0
}
14225
14226
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14227
0
{
14228
0
    ImGuiContext& g = *GImGui;
14229
0
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14230
0
    g.SettingsHandlers.push_back(*handler);
14231
0
}
14232
14233
void ImGui::RemoveSettingsHandler(const char* type_name)
14234
0
{
14235
0
    ImGuiContext& g = *GImGui;
14236
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14237
0
        g.SettingsHandlers.erase(handler);
14238
0
}
14239
14240
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14241
0
{
14242
0
    ImGuiContext& g = *GImGui;
14243
0
    const ImGuiID type_hash = ImHashStr(type_name);
14244
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14245
0
        if (handler.TypeHash == type_hash)
14246
0
            return &handler;
14247
0
    return NULL;
14248
0
}
14249
14250
// Clear all settings (windows, tables, docking etc.)
14251
void ImGui::ClearIniSettings()
14252
0
{
14253
0
    ImGuiContext& g = *GImGui;
14254
0
    g.SettingsIniData.clear();
14255
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14256
0
        if (handler.ClearAllFn != NULL)
14257
0
            handler.ClearAllFn(&g, &handler);
14258
0
}
14259
14260
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14261
0
{
14262
0
    size_t file_data_size = 0;
14263
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14264
0
    if (!file_data)
14265
0
        return;
14266
0
    if (file_data_size > 0)
14267
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14268
0
    IM_FREE(file_data);
14269
0
}
14270
14271
// Zero-tolerance, no error reporting, cheap .ini parsing
14272
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14273
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14274
0
{
14275
0
    ImGuiContext& g = *GImGui;
14276
0
    IM_ASSERT(g.Initialized);
14277
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14278
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14279
14280
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14281
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14282
0
    if (ini_size == 0)
14283
0
        ini_size = strlen(ini_data);
14284
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14285
0
    char* const buf = g.SettingsIniData.Buf.Data;
14286
0
    char* const buf_end = buf + ini_size;
14287
0
    memcpy(buf, ini_data, ini_size);
14288
0
    buf_end[0] = 0;
14289
14290
    // Call pre-read handlers
14291
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14292
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14293
0
        if (handler.ReadInitFn != NULL)
14294
0
            handler.ReadInitFn(&g, &handler);
14295
14296
0
    void* entry_data = NULL;
14297
0
    ImGuiSettingsHandler* entry_handler = NULL;
14298
14299
0
    char* line_end = NULL;
14300
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14301
0
    {
14302
        // Skip new lines markers, then find end of the line
14303
0
        while (*line == '\n' || *line == '\r')
14304
0
            line++;
14305
0
        line_end = line;
14306
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14307
0
            line_end++;
14308
0
        line_end[0] = 0;
14309
0
        if (line[0] == ';')
14310
0
            continue;
14311
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14312
0
        {
14313
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14314
0
            line_end[-1] = 0;
14315
0
            const char* name_end = line_end - 1;
14316
0
            const char* type_start = line + 1;
14317
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14318
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14319
0
            if (!type_end || !name_start)
14320
0
                continue;
14321
0
            *type_end = 0; // Overwrite first ']'
14322
0
            name_start++;  // Skip second '['
14323
0
            entry_handler = FindSettingsHandler(type_start);
14324
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14325
0
        }
14326
0
        else if (entry_handler != NULL && entry_data != NULL)
14327
0
        {
14328
            // Let type handler parse the line
14329
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14330
0
        }
14331
0
    }
14332
0
    g.SettingsLoaded = true;
14333
14334
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14335
0
    memcpy(buf, ini_data, ini_size);
14336
14337
    // Call post-read handlers
14338
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14339
0
        if (handler.ApplyAllFn != NULL)
14340
0
            handler.ApplyAllFn(&g, &handler);
14341
0
}
14342
14343
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14344
0
{
14345
0
    ImGuiContext& g = *GImGui;
14346
0
    g.SettingsDirtyTimer = 0.0f;
14347
0
    if (!ini_filename)
14348
0
        return;
14349
14350
0
    size_t ini_data_size = 0;
14351
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14352
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14353
0
    if (!f)
14354
0
        return;
14355
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14356
0
    ImFileClose(f);
14357
0
}
14358
14359
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14360
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14361
0
{
14362
0
    ImGuiContext& g = *GImGui;
14363
0
    g.SettingsDirtyTimer = 0.0f;
14364
0
    g.SettingsIniData.Buf.resize(0);
14365
0
    g.SettingsIniData.Buf.push_back(0);
14366
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14367
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14368
0
    if (out_size)
14369
0
        *out_size = (size_t)g.SettingsIniData.size();
14370
0
    return g.SettingsIniData.c_str();
14371
0
}
14372
14373
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14374
0
{
14375
0
    ImGuiContext& g = *GImGui;
14376
14377
0
    if (g.IO.ConfigDebugIniSettings == false)
14378
0
    {
14379
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14380
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14381
0
        if (const char* p = strstr(name, "###"))
14382
0
            name = p;
14383
0
    }
14384
0
    const size_t name_len = strlen(name);
14385
14386
    // Allocate chunk
14387
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14388
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14389
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14390
0
    settings->ID = ImHashStr(name, name_len);
14391
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14392
14393
0
    return settings;
14394
0
}
14395
14396
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14397
// This is called once per window .ini entry + once per newly instantiated window.
14398
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14399
0
{
14400
0
    ImGuiContext& g = *GImGui;
14401
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14402
0
        if (settings->ID == id && !settings->WantDelete)
14403
0
            return settings;
14404
0
    return NULL;
14405
0
}
14406
14407
// This is faster if you are holding on a Window already as we don't need to perform a search.
14408
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14409
0
{
14410
0
    ImGuiContext& g = *GImGui;
14411
0
    if (window->SettingsOffset != -1)
14412
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14413
0
    return FindWindowSettingsByID(window->ID);
14414
0
}
14415
14416
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14417
void ImGui::ClearWindowSettings(const char* name)
14418
0
{
14419
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14420
0
    ImGuiContext& g = *GImGui;
14421
0
    ImGuiWindow* window = FindWindowByName(name);
14422
0
    if (window != NULL)
14423
0
    {
14424
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14425
0
        InitOrLoadWindowSettings(window, NULL);
14426
0
        if (window->DockId != 0)
14427
0
            DockContextProcessUndockWindow(&g, window, true);
14428
0
    }
14429
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14430
0
        settings->WantDelete = true;
14431
0
}
14432
14433
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14434
0
{
14435
0
    ImGuiContext& g = *ctx;
14436
0
    for (ImGuiWindow* window : g.Windows)
14437
0
        window->SettingsOffset = -1;
14438
0
    g.SettingsWindows.clear();
14439
0
}
14440
14441
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14442
0
{
14443
0
    ImGuiID id = ImHashStr(name);
14444
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14445
0
    if (settings)
14446
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14447
0
    else
14448
0
        settings = ImGui::CreateNewWindowSettings(name);
14449
0
    settings->ID = id;
14450
0
    settings->WantApply = true;
14451
0
    return (void*)settings;
14452
0
}
14453
14454
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14455
0
{
14456
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14457
0
    int x, y;
14458
0
    int i;
14459
0
    ImU32 u1;
14460
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14461
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14462
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14463
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14464
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14465
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14466
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14467
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14468
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14469
0
}
14470
14471
// Apply to existing windows (if any)
14472
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14473
0
{
14474
0
    ImGuiContext& g = *ctx;
14475
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14476
0
        if (settings->WantApply)
14477
0
        {
14478
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14479
0
                ApplyWindowSettings(window, settings);
14480
0
            settings->WantApply = false;
14481
0
        }
14482
0
}
14483
14484
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14485
0
{
14486
    // Gather data from windows that were active during this session
14487
    // (if a window wasn't opened in this session we preserve its settings)
14488
0
    ImGuiContext& g = *ctx;
14489
0
    for (ImGuiWindow* window : g.Windows)
14490
0
    {
14491
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14492
0
            continue;
14493
14494
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14495
0
        if (!settings)
14496
0
        {
14497
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14498
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14499
0
        }
14500
0
        IM_ASSERT(settings->ID == window->ID);
14501
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14502
0
        settings->Size = ImVec2ih(window->SizeFull);
14503
0
        settings->ViewportId = window->ViewportId;
14504
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14505
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14506
0
        settings->DockId = window->DockId;
14507
0
        settings->ClassId = window->WindowClass.ClassId;
14508
0
        settings->DockOrder = window->DockOrder;
14509
0
        settings->Collapsed = window->Collapsed;
14510
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14511
0
        settings->WantDelete = false;
14512
0
    }
14513
14514
    // Write to text buffer
14515
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14516
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14517
0
    {
14518
0
        if (settings->WantDelete)
14519
0
            continue;
14520
0
        const char* settings_name = settings->GetName();
14521
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14522
0
        if (settings->IsChild)
14523
0
        {
14524
0
            buf->appendf("IsChild=1\n");
14525
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14526
0
        }
14527
0
        else
14528
0
        {
14529
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14530
0
            {
14531
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14532
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14533
0
            }
14534
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14535
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14536
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14537
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14538
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14539
0
            if (settings->DockId != 0)
14540
0
            {
14541
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14542
0
                if (settings->DockOrder == -1)
14543
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14544
0
                else
14545
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14546
0
                if (settings->ClassId != 0)
14547
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14548
0
            }
14549
0
        }
14550
0
        buf->append("\n");
14551
0
    }
14552
0
}
14553
14554
14555
//-----------------------------------------------------------------------------
14556
// [SECTION] LOCALIZATION
14557
//-----------------------------------------------------------------------------
14558
14559
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14560
0
{
14561
0
    ImGuiContext& g = *GImGui;
14562
0
    for (int n = 0; n < count; n++)
14563
0
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14564
0
}
14565
14566
14567
//-----------------------------------------------------------------------------
14568
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14569
//-----------------------------------------------------------------------------
14570
// - GetMainViewport()
14571
// - FindViewportByID()
14572
// - FindViewportByPlatformHandle()
14573
// - SetCurrentViewport() [Internal]
14574
// - SetWindowViewport() [Internal]
14575
// - GetWindowAlwaysWantOwnViewport() [Internal]
14576
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14577
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14578
// - TranslateWindowsInViewport() [Internal]
14579
// - ScaleWindowsInViewport() [Internal]
14580
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14581
// - UpdateViewportsNewFrame() [Internal]
14582
// - UpdateViewportsEndFrame() [Internal]
14583
// - AddUpdateViewport() [Internal]
14584
// - WindowSelectViewport() [Internal]
14585
// - WindowSyncOwnedViewport() [Internal]
14586
// - UpdatePlatformWindows()
14587
// - RenderPlatformWindowsDefault()
14588
// - FindPlatformMonitorForPos() [Internal]
14589
// - FindPlatformMonitorForRect() [Internal]
14590
// - UpdateViewportPlatformMonitor() [Internal]
14591
// - DestroyPlatformWindow() [Internal]
14592
// - DestroyPlatformWindows()
14593
//-----------------------------------------------------------------------------
14594
14595
ImGuiViewport* ImGui::GetMainViewport()
14596
0
{
14597
0
    ImGuiContext& g = *GImGui;
14598
0
    return g.Viewports[0];
14599
0
}
14600
14601
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14602
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14603
0
{
14604
0
    ImGuiContext& g = *GImGui;
14605
0
    for (ImGuiViewportP* viewport : g.Viewports)
14606
0
        if (viewport->ID == id)
14607
0
            return viewport;
14608
0
    return NULL;
14609
0
}
14610
14611
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14612
0
{
14613
0
    ImGuiContext& g = *GImGui;
14614
0
    for (ImGuiViewportP* viewport : g.Viewports)
14615
0
        if (viewport->PlatformHandle == platform_handle)
14616
0
            return viewport;
14617
0
    return NULL;
14618
0
}
14619
14620
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14621
0
{
14622
0
    ImGuiContext& g = *GImGui;
14623
0
    (void)current_window;
14624
14625
0
    if (viewport)
14626
0
        viewport->LastFrameActive = g.FrameCount;
14627
0
    if (g.CurrentViewport == viewport)
14628
0
        return;
14629
0
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14630
0
    g.CurrentViewport = viewport;
14631
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14632
14633
    // Notify platform layer of viewport changes
14634
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14635
0
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14636
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14637
0
}
14638
14639
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14640
0
{
14641
    // Abandon viewport
14642
0
    if (window->ViewportOwned && window->Viewport->Window == window)
14643
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14644
14645
0
    window->Viewport = viewport;
14646
0
    window->ViewportId = viewport->ID;
14647
0
    window->ViewportOwned = (viewport->Window == window);
14648
0
}
14649
14650
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14651
0
{
14652
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14653
0
    ImGuiContext& g = *GImGui;
14654
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14655
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14656
0
            if (!window->DockIsActive)
14657
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14658
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14659
0
                        return true;
14660
0
    return false;
14661
0
}
14662
14663
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14664
0
{
14665
0
    ImGuiContext& g = *GImGui;
14666
0
    if (window->Viewport == viewport)
14667
0
        return false;
14668
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14669
0
        return false;
14670
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14671
0
        return false;
14672
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14673
0
        return false;
14674
0
    if (GetWindowAlwaysWantOwnViewport(window))
14675
0
        return false;
14676
14677
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14678
0
    for (ImGuiWindow* window_behind : g.Windows)
14679
0
    {
14680
0
        if (window_behind == window)
14681
0
            break;
14682
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14683
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14684
0
                return false;
14685
0
    }
14686
14687
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14688
0
    ImGuiViewportP* old_viewport = window->Viewport;
14689
0
    if (window->ViewportOwned)
14690
0
        for (int n = 0; n < g.Windows.Size; n++)
14691
0
            if (g.Windows[n]->Viewport == old_viewport)
14692
0
                SetWindowViewport(g.Windows[n], viewport);
14693
0
    SetWindowViewport(window, viewport);
14694
0
    BringWindowToDisplayFront(window);
14695
14696
0
    return true;
14697
0
}
14698
14699
// FIXME: handle 0 to N host viewports
14700
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14701
0
{
14702
0
    ImGuiContext& g = *GImGui;
14703
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14704
0
}
14705
14706
// Translate Dear ImGui windows when a Host Viewport has been moved
14707
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14708
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14709
0
{
14710
0
    ImGuiContext& g = *GImGui;
14711
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14712
14713
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14714
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14715
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14716
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14717
    // and so the window will appear to teleport when releasing the mouse.
14718
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14719
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14720
0
    ImVec2 delta_pos = new_pos - old_pos;
14721
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14722
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14723
0
            TranslateWindow(window, delta_pos);
14724
0
}
14725
14726
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14727
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14728
0
{
14729
0
    ImGuiContext& g = *GImGui;
14730
0
    if (viewport->Window)
14731
0
    {
14732
0
        ScaleWindow(viewport->Window, scale);
14733
0
    }
14734
0
    else
14735
0
    {
14736
0
        for (ImGuiWindow* window : g.Windows)
14737
0
            if (window->Viewport == viewport)
14738
0
                ScaleWindow(window, scale);
14739
0
    }
14740
0
}
14741
14742
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14743
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14744
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14745
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14746
0
{
14747
0
    ImGuiContext& g = *GImGui;
14748
0
    ImGuiViewportP* best_candidate = NULL;
14749
0
    for (ImGuiViewportP* viewport : g.Viewports)
14750
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14751
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14752
0
                best_candidate = viewport;
14753
0
    return best_candidate;
14754
0
}
14755
14756
// Update viewports and monitor infos
14757
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14758
static void ImGui::UpdateViewportsNewFrame()
14759
0
{
14760
0
    ImGuiContext& g = *GImGui;
14761
0
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14762
14763
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14764
    // Update Focused status
14765
0
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14766
0
    if (viewports_enabled)
14767
0
    {
14768
0
        ImGuiViewportP* focused_viewport = NULL;
14769
0
        for (ImGuiViewportP* viewport : g.Viewports)
14770
0
        {
14771
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14772
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14773
0
            {
14774
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14775
0
                if (is_minimized)
14776
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14777
0
                else
14778
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14779
0
            }
14780
14781
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14782
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14783
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14784
0
            {
14785
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14786
0
                if (is_focused)
14787
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14788
0
                else
14789
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14790
0
                if (is_focused)
14791
0
                    focused_viewport = viewport;
14792
0
            }
14793
0
        }
14794
14795
        // Focused viewport has changed?
14796
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14797
0
        {
14798
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14799
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14800
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14801
14802
            // Store a tag so we can infer z-order easily from all our windows
14803
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14804
            // will keep the front most stamp instead of losing it back to their parent viewport.
14805
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14806
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14807
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14808
14809
            // Focus associated dear imgui window
14810
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14811
            // - if focus didn't happen because we destroyed another window (#6462)
14812
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14813
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14814
0
            if (apply_imgui_focus_on_focused_viewport)
14815
0
            {
14816
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14817
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14818
0
                if (focused_viewport->Window != NULL)
14819
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14820
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14821
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14822
0
                else
14823
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14824
0
            }
14825
0
        }
14826
0
        if (focused_viewport)
14827
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14828
0
    }
14829
14830
    // Create/update main viewport with current platform position.
14831
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14832
0
    ImGuiViewportP* main_viewport = g.Viewports[0];
14833
0
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14834
0
    IM_ASSERT(main_viewport->Window == NULL);
14835
0
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14836
0
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14837
0
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14838
0
    {
14839
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14840
0
        main_viewport_size = main_viewport->Size;
14841
0
    }
14842
0
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14843
14844
0
    g.CurrentDpiScale = 0.0f;
14845
0
    g.CurrentViewport = NULL;
14846
0
    g.MouseViewport = NULL;
14847
0
    for (int n = 0; n < g.Viewports.Size; n++)
14848
0
    {
14849
0
        ImGuiViewportP* viewport = g.Viewports[n];
14850
0
        viewport->Idx = n;
14851
14852
        // Erase unused viewports
14853
0
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14854
0
        {
14855
0
            DestroyViewport(viewport);
14856
0
            n--;
14857
0
            continue;
14858
0
        }
14859
14860
0
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14861
0
        if (viewports_enabled)
14862
0
        {
14863
            // Update Position and Size (from Platform Window to ImGui) if requested.
14864
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14865
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14866
0
            {
14867
                // Viewport->WorkPos and WorkSize will be updated below
14868
0
                if (viewport->PlatformRequestMove)
14869
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14870
0
                if (viewport->PlatformRequestResize)
14871
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14872
0
            }
14873
0
        }
14874
14875
        // Update/copy monitor info
14876
0
        UpdateViewportPlatformMonitor(viewport);
14877
14878
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14879
0
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14880
0
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14881
0
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14882
0
        viewport->UpdateWorkRect();
14883
14884
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14885
0
        viewport->Alpha = 1.0f;
14886
14887
        // Translate Dear ImGui windows when a Host Viewport has been moved
14888
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14889
0
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14890
0
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14891
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14892
14893
        // Update DPI scale
14894
0
        float new_dpi_scale;
14895
0
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14896
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14897
0
        else if (viewport->PlatformMonitor != -1)
14898
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14899
0
        else
14900
0
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14901
0
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14902
0
        {
14903
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14904
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14905
0
                ScaleWindowsInViewport(viewport, scale_factor);
14906
            //if (viewport == GetMainViewport())
14907
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14908
14909
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14910
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14911
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14912
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14913
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14914
0
        }
14915
0
        viewport->DpiScale = new_dpi_scale;
14916
0
    }
14917
14918
    // Update fallback monitor
14919
0
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
14920
0
    if (g.PlatformIO.Monitors.Size == 0)
14921
0
    {
14922
0
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14923
0
        monitor->MainPos = main_viewport->Pos;
14924
0
        monitor->MainSize = main_viewport->Size;
14925
0
        monitor->WorkPos = main_viewport->WorkPos;
14926
0
        monitor->WorkSize = main_viewport->WorkSize;
14927
0
        monitor->DpiScale = main_viewport->DpiScale;
14928
0
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
14929
0
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
14930
0
    }
14931
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
14932
0
    {
14933
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
14934
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
14935
0
    }
14936
14937
0
    if (!viewports_enabled)
14938
0
    {
14939
0
        g.MouseViewport = main_viewport;
14940
0
        return;
14941
0
    }
14942
14943
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14944
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14945
0
    ImGuiViewportP* viewport_hovered = NULL;
14946
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14947
0
    {
14948
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14949
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14950
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14951
0
    }
14952
0
    else
14953
0
    {
14954
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14955
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14956
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14957
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14958
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14959
0
    }
14960
0
    if (viewport_hovered != NULL)
14961
0
        g.MouseLastHoveredViewport = viewport_hovered;
14962
0
    else if (g.MouseLastHoveredViewport == NULL)
14963
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14964
14965
    // Update mouse reference viewport
14966
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14967
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14968
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14969
0
        g.MouseViewport = g.MovingWindow->Viewport;
14970
0
    else
14971
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14972
14973
    // When dragging something, always refer to the last hovered viewport.
14974
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14975
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14976
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14977
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14978
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14979
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14980
0
        viewport_hovered = g.MouseLastHoveredViewport;
14981
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14982
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14983
0
            g.MouseViewport = viewport_hovered;
14984
14985
0
    IM_ASSERT(g.MouseViewport != NULL);
14986
0
}
14987
14988
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14989
static void ImGui::UpdateViewportsEndFrame()
14990
0
{
14991
0
    ImGuiContext& g = *GImGui;
14992
0
    g.PlatformIO.Viewports.resize(0);
14993
0
    for (int i = 0; i < g.Viewports.Size; i++)
14994
0
    {
14995
0
        ImGuiViewportP* viewport = g.Viewports[i];
14996
0
        viewport->LastPos = viewport->Pos;
14997
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14998
0
            if (i > 0) // Always include main viewport in the list
14999
0
                continue;
15000
0
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
15001
0
            continue;
15002
0
        if (i > 0)
15003
0
            IM_ASSERT(viewport->Window != NULL);
15004
0
        g.PlatformIO.Viewports.push_back(viewport);
15005
0
    }
15006
0
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
15007
0
}
15008
15009
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
15010
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
15011
0
{
15012
0
    ImGuiContext& g = *GImGui;
15013
0
    IM_ASSERT(id != 0);
15014
15015
0
    flags |= ImGuiViewportFlags_IsPlatformWindow;
15016
0
    if (window != NULL)
15017
0
    {
15018
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
15019
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
15020
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
15021
0
            flags |= ImGuiViewportFlags_NoInputs;
15022
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
15023
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15024
0
    }
15025
15026
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15027
0
    if (viewport)
15028
0
    {
15029
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15030
0
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15031
0
            viewport->Pos = pos;
15032
0
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15033
0
            viewport->Size = size;
15034
0
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15035
0
    }
15036
0
    else
15037
0
    {
15038
        // New viewport
15039
0
        viewport = IM_NEW(ImGuiViewportP)();
15040
0
        viewport->ID = id;
15041
0
        viewport->Idx = g.Viewports.Size;
15042
0
        viewport->Pos = viewport->LastPos = pos;
15043
0
        viewport->Size = size;
15044
0
        viewport->Flags = flags;
15045
0
        UpdateViewportPlatformMonitor(viewport);
15046
0
        g.Viewports.push_back(viewport);
15047
0
        g.ViewportCreatedCount++;
15048
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15049
15050
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15051
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15052
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15053
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15054
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15055
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15056
15057
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15058
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15059
0
        if (viewport->PlatformMonitor != -1)
15060
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15061
0
    }
15062
15063
0
    viewport->Window = window;
15064
0
    viewport->LastFrameActive = g.FrameCount;
15065
0
    viewport->UpdateWorkRect();
15066
0
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15067
15068
0
    if (window != NULL)
15069
0
        window->ViewportOwned = true;
15070
15071
0
    return viewport;
15072
0
}
15073
15074
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15075
0
{
15076
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15077
0
    ImGuiContext& g = *GImGui;
15078
0
    for (ImGuiWindow* window : g.Windows)
15079
0
    {
15080
0
        if (window->Viewport != viewport)
15081
0
            continue;
15082
0
        window->Viewport = NULL;
15083
0
        window->ViewportOwned = false;
15084
0
    }
15085
0
    if (viewport == g.MouseLastHoveredViewport)
15086
0
        g.MouseLastHoveredViewport = NULL;
15087
15088
    // Destroy
15089
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15090
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15091
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15092
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15093
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15094
0
    IM_DELETE(viewport);
15095
0
}
15096
15097
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15098
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15099
0
{
15100
0
    ImGuiContext& g = *GImGui;
15101
0
    ImGuiWindowFlags flags = window->Flags;
15102
0
    window->ViewportAllowPlatformMonitorExtend = -1;
15103
15104
    // Restore main viewport if multi-viewport is not supported by the backend
15105
0
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15106
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15107
0
    {
15108
0
        SetWindowViewport(window, main_viewport);
15109
0
        return;
15110
0
    }
15111
0
    window->ViewportOwned = false;
15112
15113
    // Appearing popups reset their viewport so they can inherit again
15114
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15115
0
    {
15116
0
        window->Viewport = NULL;
15117
0
        window->ViewportId = 0;
15118
0
    }
15119
15120
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15121
0
    {
15122
        // By default inherit from parent window
15123
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15124
0
            window->Viewport = window->ParentWindow->Viewport;
15125
15126
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15127
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15128
0
        {
15129
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15130
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15131
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15132
0
        }
15133
0
    }
15134
15135
0
    bool lock_viewport = false;
15136
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15137
0
    {
15138
        // Code explicitly request a viewport
15139
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15140
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15141
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15142
0
        {
15143
0
            window->Viewport->Window = window;
15144
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15145
0
        }
15146
0
        lock_viewport = true;
15147
0
    }
15148
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15149
0
    {
15150
        // Always inherit viewport from parent window
15151
0
        if (window->DockNode && window->DockNode->HostWindow)
15152
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15153
0
        window->Viewport = window->ParentWindow->Viewport;
15154
0
    }
15155
0
    else if (window->DockNode && window->DockNode->HostWindow)
15156
0
    {
15157
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15158
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15159
0
    }
15160
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15161
0
    {
15162
0
        window->Viewport = g.MouseViewport;
15163
0
    }
15164
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15165
0
    {
15166
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15167
0
    }
15168
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15169
0
    {
15170
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15171
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15172
0
    }
15173
0
    else
15174
0
    {
15175
        // Merge into host viewport?
15176
        // We cannot test window->ViewportOwned as it set lower in the function.
15177
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15178
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15179
0
        if (try_to_merge_into_host_viewport)
15180
0
            UpdateTryMergeWindowIntoHostViewports(window);
15181
0
    }
15182
15183
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15184
0
    if (window->Viewport == NULL)
15185
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15186
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15187
15188
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15189
0
    if (!lock_viewport)
15190
0
    {
15191
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15192
0
        {
15193
            // We need to take account of the possibility that mouse may become invalid.
15194
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15195
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15196
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15197
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15198
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15199
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15200
0
            else
15201
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15202
0
        }
15203
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15204
0
        {
15205
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15206
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15207
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15208
0
            {
15209
                // Steal/transfer ownership
15210
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15211
0
                window->Viewport->Window = window;
15212
0
                window->Viewport->ID = window->ID;
15213
0
                window->Viewport->LastNameHash = 0;
15214
0
            }
15215
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15216
0
            {
15217
                // New viewport
15218
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15219
0
            }
15220
0
        }
15221
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15222
0
        {
15223
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15224
            // Child windows are kept contained within their parent.
15225
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15226
0
        }
15227
0
    }
15228
15229
    // Update flags
15230
0
    window->ViewportOwned = (window == window->Viewport->Window);
15231
0
    window->ViewportId = window->Viewport->ID;
15232
15233
    // If the OS window has a title bar, hide our imgui title bar
15234
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15235
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15236
0
}
15237
15238
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15239
0
{
15240
0
    ImGuiContext& g = *GImGui;
15241
15242
0
    bool viewport_rect_changed = false;
15243
15244
    // Synchronize window --> viewport in most situations
15245
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15246
0
    if (window->Viewport->PlatformRequestMove)
15247
0
    {
15248
0
        window->Pos = window->Viewport->Pos;
15249
0
        MarkIniSettingsDirty(window);
15250
0
    }
15251
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15252
0
    {
15253
0
        viewport_rect_changed = true;
15254
0
        window->Viewport->Pos = window->Pos;
15255
0
    }
15256
15257
0
    if (window->Viewport->PlatformRequestResize)
15258
0
    {
15259
0
        window->Size = window->SizeFull = window->Viewport->Size;
15260
0
        MarkIniSettingsDirty(window);
15261
0
    }
15262
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15263
0
    {
15264
0
        viewport_rect_changed = true;
15265
0
        window->Viewport->Size = window->Size;
15266
0
    }
15267
0
    window->Viewport->UpdateWorkRect();
15268
15269
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15270
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15271
0
    if (viewport_rect_changed)
15272
0
        UpdateViewportPlatformMonitor(window->Viewport);
15273
15274
    // Update common viewport flags
15275
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15276
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15277
0
    ImGuiWindowFlags window_flags = window->Flags;
15278
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15279
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15280
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15281
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15282
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15283
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15284
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15285
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15286
15287
    // Not correct to set modal as topmost because:
15288
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15289
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15290
    //if (flags & ImGuiWindowFlags_Modal)
15291
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15292
15293
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15294
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15295
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15296
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15297
0
    if (is_short_lived_floating_window && !is_modal)
15298
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15299
15300
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15301
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15302
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15303
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15304
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15305
15306
    // We can also tell the backend that clearing the platform window won't be necessary,
15307
    // as our window background is filling the viewport and we have disabled BgAlpha.
15308
    // FIXME: Work on support for per-viewport transparency (#2766)
15309
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15310
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15311
15312
0
    window->Viewport->Flags = viewport_flags;
15313
15314
    // Update parent viewport ID
15315
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15316
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15317
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15318
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15319
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15320
0
    else
15321
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15322
0
}
15323
15324
// Called by user at the end of the main loop, after EndFrame()
15325
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15326
void ImGui::UpdatePlatformWindows()
15327
0
{
15328
0
    ImGuiContext& g = *GImGui;
15329
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15330
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15331
0
    g.FrameCountPlatformEnded = g.FrameCount;
15332
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15333
0
        return;
15334
15335
    // Create/resize/destroy platform windows to match each active viewport.
15336
    // Skip the main viewport (index 0), which is always fully handled by the application!
15337
0
    for (int i = 1; i < g.Viewports.Size; i++)
15338
0
    {
15339
0
        ImGuiViewportP* viewport = g.Viewports[i];
15340
15341
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15342
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15343
0
        bool destroy_platform_window = false;
15344
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15345
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15346
0
        if (destroy_platform_window)
15347
0
        {
15348
0
            DestroyPlatformWindow(viewport);
15349
0
            continue;
15350
0
        }
15351
15352
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15353
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15354
0
            continue;
15355
15356
        // Create window
15357
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15358
0
        if (is_new_platform_window)
15359
0
        {
15360
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15361
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15362
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15363
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15364
0
            g.PlatformWindowsCreatedCount++;
15365
0
            viewport->LastNameHash = 0;
15366
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15367
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15368
0
            viewport->PlatformWindowCreated = true;
15369
0
        }
15370
15371
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15372
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15373
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15374
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15375
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15376
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15377
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15378
0
        viewport->LastPlatformPos = viewport->Pos;
15379
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15380
15381
        // Update title bar (if it changed)
15382
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15383
0
        {
15384
0
            const char* title_begin = window_for_title->Name;
15385
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15386
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15387
0
            if (viewport->LastNameHash != title_hash)
15388
0
            {
15389
0
                char title_end_backup_c = *title_end;
15390
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15391
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15392
0
                *title_end = title_end_backup_c;
15393
0
                viewport->LastNameHash = title_hash;
15394
0
            }
15395
0
        }
15396
15397
        // Update alpha (if it changed)
15398
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15399
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15400
0
        viewport->LastAlpha = viewport->Alpha;
15401
15402
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15403
0
        if (g.PlatformIO.Platform_UpdateWindow)
15404
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15405
15406
0
        if (is_new_platform_window)
15407
0
        {
15408
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15409
0
            if (g.FrameCount < 3)
15410
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15411
15412
            // Show window
15413
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15414
15415
            // Even without focus, we assume the window becomes front-most.
15416
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15417
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15418
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15419
0
        }
15420
15421
        // Clear request flags
15422
0
        viewport->ClearRequestFlags();
15423
0
    }
15424
0
}
15425
15426
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15427
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15428
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15429
//
15430
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15431
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15432
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15433
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15434
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15435
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15436
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15437
//
15438
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15439
0
{
15440
    // Skip the main viewport (index 0), which is always fully handled by the application!
15441
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15442
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15443
0
    {
15444
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15445
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15446
0
            continue;
15447
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15448
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15449
0
    }
15450
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15451
0
    {
15452
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15453
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15454
0
            continue;
15455
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15456
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15457
0
    }
15458
0
}
15459
15460
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15461
0
{
15462
0
    ImGuiContext& g = *GImGui;
15463
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15464
0
    {
15465
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15466
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15467
0
            return monitor_n;
15468
0
    }
15469
0
    return -1;
15470
0
}
15471
15472
// Search for the monitor with the largest intersection area with the given rectangle
15473
// We generally try to avoid searching loops but the monitor count should be very small here
15474
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15475
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15476
0
{
15477
0
    ImGuiContext& g = *GImGui;
15478
15479
0
    const int monitor_count = g.PlatformIO.Monitors.Size;
15480
0
    if (monitor_count <= 1)
15481
0
        return monitor_count - 1;
15482
15483
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15484
    // This is necessary for tooltips which always resize down to zero at first.
15485
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15486
0
    int best_monitor_n = -1;
15487
0
    float best_monitor_surface = 0.001f;
15488
15489
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15490
0
    {
15491
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15492
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15493
0
        if (monitor_rect.Contains(rect))
15494
0
            return monitor_n;
15495
0
        ImRect overlapping_rect = rect;
15496
0
        overlapping_rect.ClipWithFull(monitor_rect);
15497
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15498
0
        if (overlapping_surface < best_monitor_surface)
15499
0
            continue;
15500
0
        best_monitor_surface = overlapping_surface;
15501
0
        best_monitor_n = monitor_n;
15502
0
    }
15503
0
    return best_monitor_n;
15504
0
}
15505
15506
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15507
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15508
0
{
15509
0
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15510
0
}
15511
15512
// Return value is always != NULL, but don't hold on it across frames.
15513
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15514
0
{
15515
0
    ImGuiContext& g = *GImGui;
15516
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15517
0
    int monitor_idx = viewport->PlatformMonitor;
15518
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15519
0
        return &g.PlatformIO.Monitors[monitor_idx];
15520
0
    return &g.FallbackMonitor;
15521
0
}
15522
15523
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15524
0
{
15525
0
    ImGuiContext& g = *GImGui;
15526
0
    if (viewport->PlatformWindowCreated)
15527
0
    {
15528
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15529
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15530
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15531
0
        if (g.PlatformIO.Platform_DestroyWindow)
15532
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15533
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15534
15535
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15536
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15537
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15538
0
            viewport->PlatformWindowCreated = false;
15539
0
    }
15540
0
    else
15541
0
    {
15542
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15543
0
    }
15544
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15545
0
    viewport->ClearRequestFlags();
15546
0
}
15547
15548
void ImGui::DestroyPlatformWindows()
15549
0
{
15550
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15551
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15552
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15553
    // code to operator a consistent manner.
15554
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15555
    // crashing if it doesn't have data stored.
15556
0
    ImGuiContext& g = *GImGui;
15557
0
    for (ImGuiViewportP* viewport : g.Viewports)
15558
0
        DestroyPlatformWindow(viewport);
15559
0
}
15560
15561
15562
//-----------------------------------------------------------------------------
15563
// [SECTION] DOCKING
15564
//-----------------------------------------------------------------------------
15565
// Docking: Internal Types
15566
// Docking: Forward Declarations
15567
// Docking: ImGuiDockContext
15568
// Docking: ImGuiDockContext Docking/Undocking functions
15569
// Docking: ImGuiDockNode
15570
// Docking: ImGuiDockNode Tree manipulation functions
15571
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15572
// Docking: Builder Functions
15573
// Docking: Begin/End Support Functions (called from Begin/End)
15574
// Docking: Settings
15575
//-----------------------------------------------------------------------------
15576
15577
//-----------------------------------------------------------------------------
15578
// Typical Docking call flow: (root level is generally public API):
15579
//-----------------------------------------------------------------------------
15580
// - NewFrame()                               new dear imgui frame
15581
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15582
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15583
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15584
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15585
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15586
//    | - DockContextProcessDock()            - process one docking request
15587
//    | - DockNodeUpdate()
15588
//    |   - DockNodeUpdateForRootNode()
15589
//    |     - DockNodeUpdateFlagsAndCollapse()
15590
//    |     - DockNodeFindInfo()
15591
//    |   - destroy unused node or tab bar
15592
//    |   - create dock node host window
15593
//    |      - Begin() etc.
15594
//    |   - DockNodeStartMouseMovingWindow()
15595
//    |   - DockNodeTreeUpdatePosSize()
15596
//    |   - DockNodeTreeUpdateSplitter()
15597
//    |   - draw node background
15598
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15599
//    |     - DockNodeAddTabBar()
15600
//    |     - DockNodeWindowMenuUpdate()
15601
//    |     - DockNodeCalcTabBarLayout()
15602
//    |     - BeginTabBarEx()
15603
//    |     - TabItemEx() calls
15604
//    |     - EndTabBar()
15605
//    |   - BeginDockableDragDropTarget()
15606
//    |      - DockNodeUpdate()               - recurse into child nodes...
15607
//-----------------------------------------------------------------------------
15608
// - DockSpace()                              user submit a dockspace into a window
15609
//    | Begin(Child)                          - create a child window
15610
//    | DockNodeUpdate()                      - call main dock node update function
15611
//    | End(Child)
15612
//    | ItemSize()
15613
//-----------------------------------------------------------------------------
15614
// - Begin()
15615
//    | BeginDocked()
15616
//    | BeginDockableDragDropSource()
15617
//    | BeginDockableDragDropTarget()
15618
//    | - DockNodePreviewDockRender()
15619
//-----------------------------------------------------------------------------
15620
// - EndFrame()
15621
//    | DockContextEndFrame()
15622
//-----------------------------------------------------------------------------
15623
15624
//-----------------------------------------------------------------------------
15625
// Docking: Internal Types
15626
//-----------------------------------------------------------------------------
15627
// - ImGuiDockRequestType
15628
// - ImGuiDockRequest
15629
// - ImGuiDockPreviewData
15630
// - ImGuiDockNodeSettings
15631
// - ImGuiDockContext
15632
//-----------------------------------------------------------------------------
15633
15634
enum ImGuiDockRequestType
15635
{
15636
    ImGuiDockRequestType_None = 0,
15637
    ImGuiDockRequestType_Dock,
15638
    ImGuiDockRequestType_Undock,
15639
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15640
};
15641
15642
struct ImGuiDockRequest
15643
{
15644
    ImGuiDockRequestType    Type;
15645
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15646
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15647
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15648
    ImGuiDir                DockSplitDir;
15649
    float                   DockSplitRatio;
15650
    bool                    DockSplitOuter;
15651
    ImGuiWindow*            UndockTargetWindow;
15652
    ImGuiDockNode*          UndockTargetNode;
15653
15654
    ImGuiDockRequest()
15655
0
    {
15656
0
        Type = ImGuiDockRequestType_None;
15657
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15658
0
        DockTargetNode = UndockTargetNode = NULL;
15659
0
        DockSplitDir = ImGuiDir_None;
15660
0
        DockSplitRatio = 0.5f;
15661
0
        DockSplitOuter = false;
15662
0
    }
15663
};
15664
15665
struct ImGuiDockPreviewData
15666
{
15667
    ImGuiDockNode   FutureNode;
15668
    bool            IsDropAllowed;
15669
    bool            IsCenterAvailable;
15670
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15671
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15672
    ImGuiDockNode*  SplitNode;
15673
    ImGuiDir        SplitDir;
15674
    float           SplitRatio;
15675
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15676
15677
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15678
};
15679
15680
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15681
struct ImGuiDockNodeSettings
15682
{
15683
    ImGuiID             ID;
15684
    ImGuiID             ParentNodeId;
15685
    ImGuiID             ParentWindowId;
15686
    ImGuiID             SelectedTabId;
15687
    signed char         SplitAxis;
15688
    char                Depth;
15689
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15690
    ImVec2ih            Pos;
15691
    ImVec2ih            Size;
15692
    ImVec2ih            SizeRef;
15693
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15694
};
15695
15696
//-----------------------------------------------------------------------------
15697
// Docking: Forward Declarations
15698
//-----------------------------------------------------------------------------
15699
15700
namespace ImGui
15701
{
15702
    // ImGuiDockContext
15703
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15704
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15705
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15706
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15707
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15708
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15709
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15710
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15711
15712
    // ImGuiDockNode
15713
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15714
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15715
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15716
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15717
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15718
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15719
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15720
    static void             DockNodeUpdate(ImGuiDockNode* node);
15721
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15722
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15723
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15724
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15725
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15726
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15727
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15728
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15729
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15730
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15731
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15732
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15733
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15734
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15735
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15736
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15737
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15738
15739
    // ImGuiDockNode tree manipulations
15740
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15741
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15742
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15743
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15744
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15745
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15746
15747
    // Settings
15748
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15749
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15750
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15751
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15752
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15753
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15754
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15755
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15756
}
15757
15758
//-----------------------------------------------------------------------------
15759
// Docking: ImGuiDockContext
15760
//-----------------------------------------------------------------------------
15761
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15762
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15763
// At boot time only, we run a simple GC to remove nodes that have no references.
15764
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15765
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15766
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15767
//-----------------------------------------------------------------------------
15768
// - DockContextInitialize()
15769
// - DockContextShutdown()
15770
// - DockContextClearNodes()
15771
// - DockContextRebuildNodes()
15772
// - DockContextNewFrameUpdateUndocking()
15773
// - DockContextNewFrameUpdateDocking()
15774
// - DockContextEndFrame()
15775
// - DockContextFindNodeByID()
15776
// - DockContextBindNodeToWindow()
15777
// - DockContextGenNodeID()
15778
// - DockContextAddNode()
15779
// - DockContextRemoveNode()
15780
// - ImGuiDockContextPruneNodeData
15781
// - DockContextPruneUnusedSettingsNodes()
15782
// - DockContextBuildNodesFromSettings()
15783
// - DockContextBuildAddWindowsToNodes()
15784
//-----------------------------------------------------------------------------
15785
15786
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15787
0
{
15788
0
    ImGuiContext& g = *ctx;
15789
15790
    // Add .ini handle for persistent docking data
15791
0
    ImGuiSettingsHandler ini_handler;
15792
0
    ini_handler.TypeName = "Docking";
15793
0
    ini_handler.TypeHash = ImHashStr("Docking");
15794
0
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15795
0
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15796
0
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15797
0
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15798
0
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15799
0
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15800
0
    g.SettingsHandlers.push_back(ini_handler);
15801
15802
0
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15803
0
}
15804
15805
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15806
0
{
15807
0
    ImGuiDockContext* dc = &ctx->DockContext;
15808
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15809
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15810
0
            IM_DELETE(node);
15811
0
}
15812
15813
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15814
0
{
15815
0
    IM_UNUSED(ctx);
15816
0
    IM_ASSERT(ctx == GImGui);
15817
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15818
0
    DockBuilderRemoveNodeChildNodes(root_id);
15819
0
}
15820
15821
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15822
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15823
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15824
0
{
15825
0
    ImGuiContext& g = *ctx;
15826
0
    ImGuiDockContext* dc = &ctx->DockContext;
15827
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15828
0
    SaveIniSettingsToMemory();
15829
0
    ImGuiID root_id = 0; // Rebuild all
15830
0
    DockContextClearNodes(ctx, root_id, false);
15831
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15832
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15833
0
}
15834
15835
// Docking context update function, called by NewFrame()
15836
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15837
0
{
15838
0
    ImGuiContext& g = *ctx;
15839
0
    ImGuiDockContext* dc = &ctx->DockContext;
15840
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15841
0
    {
15842
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15843
0
            DockContextClearNodes(ctx, 0, true);
15844
0
        return;
15845
0
    }
15846
15847
    // Setting NoSplit at runtime merges all nodes
15848
0
    if (g.IO.ConfigDockingNoSplit)
15849
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15850
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15851
0
                if (node->IsRootNode() && node->IsSplitNode())
15852
0
                {
15853
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15854
                    //dc->WantFullRebuild = true;
15855
0
                }
15856
15857
    // Process full rebuild
15858
#if 0
15859
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15860
        dc->WantFullRebuild = true;
15861
#endif
15862
0
    if (dc->WantFullRebuild)
15863
0
    {
15864
0
        DockContextRebuildNodes(ctx);
15865
0
        dc->WantFullRebuild = false;
15866
0
    }
15867
15868
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15869
0
    for (ImGuiDockRequest& req : dc->Requests)
15870
0
    {
15871
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15872
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15873
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15874
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15875
0
    }
15876
0
}
15877
15878
// Docking context update function, called by NewFrame()
15879
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15880
0
{
15881
0
    ImGuiContext& g = *ctx;
15882
0
    ImGuiDockContext* dc = &ctx->DockContext;
15883
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15884
0
        return;
15885
15886
    // [DEBUG] Store hovered dock node.
15887
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15888
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15889
0
    g.DebugHoveredDockNode = NULL;
15890
0
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15891
0
    {
15892
0
        if (hovered_window->DockNodeAsHost)
15893
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15894
0
        else if (hovered_window->RootWindow->DockNode)
15895
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15896
0
    }
15897
15898
    // Process Docking requests
15899
0
    for (ImGuiDockRequest& req : dc->Requests)
15900
0
        if (req.Type == ImGuiDockRequestType_Dock)
15901
0
            DockContextProcessDock(ctx, &req);
15902
0
    dc->Requests.resize(0);
15903
15904
    // Create windows for each automatic docking nodes
15905
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15906
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15907
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15908
0
            if (node->IsFloatingNode())
15909
0
                DockNodeUpdate(node);
15910
0
}
15911
15912
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15913
0
{
15914
    // Draw backgrounds of node missing their window
15915
0
    ImGuiContext& g = *ctx;
15916
0
    ImGuiDockContext* dc = &g.DockContext;
15917
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15918
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15919
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15920
0
            {
15921
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15922
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15923
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15924
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15925
0
            }
15926
0
}
15927
15928
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15929
0
{
15930
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15931
0
}
15932
15933
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15934
0
{
15935
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15936
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15937
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15938
0
    ImGuiID id = 0x0001;
15939
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15940
0
        id++;
15941
0
    return id;
15942
0
}
15943
15944
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15945
0
{
15946
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15947
0
    ImGuiContext& g = *ctx;
15948
0
    if (id == 0)
15949
0
        id = DockContextGenNodeID(ctx);
15950
0
    else
15951
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15952
15953
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15954
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15955
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15956
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15957
0
    return node;
15958
0
}
15959
15960
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15961
0
{
15962
0
    ImGuiContext& g = *ctx;
15963
0
    ImGuiDockContext* dc = &ctx->DockContext;
15964
15965
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15966
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15967
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15968
0
    IM_ASSERT(node->Windows.Size == 0);
15969
15970
0
    if (node->HostWindow)
15971
0
        node->HostWindow->DockNodeAsHost = NULL;
15972
15973
0
    ImGuiDockNode* parent_node = node->ParentNode;
15974
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15975
0
    if (merge)
15976
0
    {
15977
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15978
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15979
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15980
0
    }
15981
0
    else
15982
0
    {
15983
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15984
0
            if (parent_node->ChildNodes[n] == node)
15985
0
                node->ParentNode->ChildNodes[n] = NULL;
15986
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15987
0
        IM_DELETE(node);
15988
0
    }
15989
0
}
15990
15991
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15992
0
{
15993
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15994
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15995
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15996
0
}
15997
15998
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15999
struct ImGuiDockContextPruneNodeData
16000
{
16001
    int         CountWindows, CountChildWindows, CountChildNodes;
16002
    ImGuiID     RootId;
16003
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
16004
};
16005
16006
// Garbage collect unused nodes (run once at init time)
16007
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
16008
0
{
16009
0
    ImGuiContext& g = *ctx;
16010
0
    ImGuiDockContext* dc = &ctx->DockContext;
16011
0
    IM_ASSERT(g.Windows.Size == 0);
16012
16013
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
16014
0
    pool.Reserve(dc->NodesSettings.Size);
16015
16016
    // Count child nodes and compute RootID
16017
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16018
0
    {
16019
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16020
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
16021
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
16022
0
        if (settings->ParentNodeId)
16023
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
16024
0
    }
16025
16026
    // Count reference to dock ids from dockspaces
16027
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16028
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16029
0
    {
16030
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16031
0
        if (settings->ParentWindowId != 0)
16032
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16033
0
                if (window_settings->DockId)
16034
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16035
0
                        data->CountChildNodes++;
16036
0
    }
16037
16038
    // Count reference to dock ids from window settings
16039
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16040
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16041
0
        if (ImGuiID dock_id = settings->DockId)
16042
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16043
0
            {
16044
0
                data->CountWindows++;
16045
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16046
0
                    data_root->CountChildWindows++;
16047
0
            }
16048
16049
    // Prune
16050
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16051
0
    {
16052
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16053
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16054
0
        if (data->CountWindows > 1)
16055
0
            continue;
16056
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16057
16058
0
        bool remove = false;
16059
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16060
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16061
0
        remove |= (data_root->CountChildWindows == 0);
16062
0
        if (remove)
16063
0
        {
16064
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16065
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16066
0
            settings->ID = 0;
16067
0
        }
16068
0
    }
16069
0
}
16070
16071
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16072
0
{
16073
    // Build nodes
16074
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16075
0
    {
16076
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16077
0
        if (settings->ID == 0)
16078
0
            continue;
16079
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16080
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16081
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16082
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16083
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16084
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16085
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16086
0
            node->ParentNode->ChildNodes[0] = node;
16087
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16088
0
            node->ParentNode->ChildNodes[1] = node;
16089
0
        node->SelectedTabId = settings->SelectedTabId;
16090
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16091
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16092
16093
        // Bind host window immediately if it already exist (in case of a rebuild)
16094
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16095
0
        char host_window_title[20];
16096
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16097
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16098
0
    }
16099
0
}
16100
16101
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16102
0
{
16103
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16104
0
    ImGuiContext& g = *ctx;
16105
0
    for (ImGuiWindow* window : g.Windows)
16106
0
    {
16107
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16108
0
            continue;
16109
0
        if (window->DockNode != NULL)
16110
0
            continue;
16111
16112
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16113
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16114
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16115
0
            DockNodeAddWindow(node, window, true);
16116
0
    }
16117
0
}
16118
16119
//-----------------------------------------------------------------------------
16120
// Docking: ImGuiDockContext Docking/Undocking functions
16121
//-----------------------------------------------------------------------------
16122
// - DockContextQueueDock()
16123
// - DockContextQueueUndockWindow()
16124
// - DockContextQueueUndockNode()
16125
// - DockContextQueueNotifyRemovedNode()
16126
// - DockContextProcessDock()
16127
// - DockContextProcessUndockWindow()
16128
// - DockContextProcessUndockNode()
16129
// - DockContextCalcDropPosForDocking()
16130
//-----------------------------------------------------------------------------
16131
16132
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16133
0
{
16134
0
    IM_ASSERT(target != payload);
16135
0
    ImGuiDockRequest req;
16136
0
    req.Type = ImGuiDockRequestType_Dock;
16137
0
    req.DockTargetWindow = target;
16138
0
    req.DockTargetNode = target_node;
16139
0
    req.DockPayload = payload;
16140
0
    req.DockSplitDir = split_dir;
16141
0
    req.DockSplitRatio = split_ratio;
16142
0
    req.DockSplitOuter = split_outer;
16143
0
    ctx->DockContext.Requests.push_back(req);
16144
0
}
16145
16146
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16147
0
{
16148
0
    ImGuiDockRequest req;
16149
0
    req.Type = ImGuiDockRequestType_Undock;
16150
0
    req.UndockTargetWindow = window;
16151
0
    ctx->DockContext.Requests.push_back(req);
16152
0
}
16153
16154
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16155
0
{
16156
0
    ImGuiDockRequest req;
16157
0
    req.Type = ImGuiDockRequestType_Undock;
16158
0
    req.UndockTargetNode = node;
16159
0
    ctx->DockContext.Requests.push_back(req);
16160
0
}
16161
16162
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16163
0
{
16164
0
    ImGuiDockContext* dc = &ctx->DockContext;
16165
0
    for (ImGuiDockRequest& req : dc->Requests)
16166
0
        if (req.DockTargetNode == node)
16167
0
            req.Type = ImGuiDockRequestType_None;
16168
0
}
16169
16170
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16171
0
{
16172
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16173
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16174
16175
0
    ImGuiContext& g = *ctx;
16176
0
    IM_UNUSED(g);
16177
16178
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16179
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16180
0
    ImGuiDockNode* node = req->DockTargetNode;
16181
0
    if (payload_window)
16182
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16183
0
    else
16184
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16185
16186
    // Decide which Tab will be selected at the end of the operation
16187
0
    ImGuiID next_selected_id = 0;
16188
0
    ImGuiDockNode* payload_node = NULL;
16189
0
    if (payload_window)
16190
0
    {
16191
0
        payload_node = payload_window->DockNodeAsHost;
16192
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16193
0
        if (payload_node && payload_node->IsLeafNode())
16194
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16195
0
        if (payload_node == NULL)
16196
0
            next_selected_id = payload_window->TabId;
16197
0
    }
16198
16199
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16200
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16201
0
    if (node)
16202
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16203
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16204
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16205
16206
    // Create new node and add existing window to it
16207
0
    if (node == NULL)
16208
0
    {
16209
0
        node = DockContextAddNode(ctx, 0);
16210
0
        node->Pos = target_window->Pos;
16211
0
        node->Size = target_window->Size;
16212
0
        if (target_window->DockNodeAsHost == NULL)
16213
0
        {
16214
0
            DockNodeAddWindow(node, target_window, true);
16215
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16216
0
            target_window->DockIsActive = true;
16217
0
        }
16218
0
    }
16219
16220
0
    ImGuiDir split_dir = req->DockSplitDir;
16221
0
    if (split_dir != ImGuiDir_None)
16222
0
    {
16223
        // Split into two, one side will be our payload node unless we are dropping a loose window
16224
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16225
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16226
0
        const float split_ratio = req->DockSplitRatio;
16227
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16228
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16229
0
        new_node->HostWindow = node->HostWindow;
16230
0
        node = new_node;
16231
0
    }
16232
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16233
16234
0
    if (node != payload_node)
16235
0
    {
16236
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16237
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16238
0
        {
16239
0
            DockNodeAddTabBar(node);
16240
0
            for (int n = 0; n < node->Windows.Size; n++)
16241
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16242
0
        }
16243
16244
0
        if (payload_node != NULL)
16245
0
        {
16246
            // Transfer full payload node (with 1+ child windows or child nodes)
16247
0
            if (payload_node->IsSplitNode())
16248
0
            {
16249
0
                if (node->Windows.Size > 0)
16250
0
                {
16251
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16252
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16253
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16254
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16255
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16256
0
                    if (visible_node->TabBar)
16257
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16258
0
                    DockNodeMoveWindows(node, visible_node);
16259
0
                    DockNodeMoveWindows(visible_node, node);
16260
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16261
0
                }
16262
0
                if (node->IsCentralNode())
16263
0
                {
16264
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16265
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16266
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16267
0
                    IM_ASSERT(last_focused_node != NULL);
16268
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16269
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16270
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16271
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16272
0
                    last_focused_root_node->CentralNode = last_focused_node;
16273
0
                }
16274
16275
0
                IM_ASSERT(node->Windows.Size == 0);
16276
0
                DockNodeMoveChildNodes(node, payload_node);
16277
0
            }
16278
0
            else
16279
0
            {
16280
0
                const ImGuiID payload_dock_id = payload_node->ID;
16281
0
                DockNodeMoveWindows(node, payload_node);
16282
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16283
0
            }
16284
0
            DockContextRemoveNode(ctx, payload_node, true);
16285
0
        }
16286
0
        else if (payload_window)
16287
0
        {
16288
            // Transfer single window
16289
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16290
0
            node->VisibleWindow = payload_window;
16291
0
            DockNodeAddWindow(node, payload_window, true);
16292
0
            if (payload_dock_id != 0)
16293
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16294
0
        }
16295
0
    }
16296
0
    else
16297
0
    {
16298
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16299
0
        node->WantHiddenTabBarUpdate = true;
16300
0
    }
16301
16302
    // Update selection immediately
16303
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16304
0
        tab_bar->NextSelectedTabId = next_selected_id;
16305
0
    MarkIniSettingsDirty();
16306
0
}
16307
16308
// Problem:
16309
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16310
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16311
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16312
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16313
// Solution:
16314
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16315
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16316
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16317
0
{
16318
0
    if (ref_viewport == NULL)
16319
0
        return size;
16320
16321
0
    ImGuiContext& g = *GImGui;
16322
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16323
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16324
0
    {
16325
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16326
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16327
0
    }
16328
0
    return ImMin(size, max_size);
16329
0
}
16330
16331
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16332
0
{
16333
0
    ImGuiContext& g = *ctx;
16334
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16335
0
    if (window->DockNode)
16336
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16337
0
    else
16338
0
        window->DockId = 0;
16339
0
    window->Collapsed = false;
16340
0
    window->DockIsActive = false;
16341
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16342
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16343
16344
0
    MarkIniSettingsDirty();
16345
0
}
16346
16347
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16348
0
{
16349
0
    ImGuiContext& g = *ctx;
16350
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16351
0
    IM_ASSERT(node->IsLeafNode());
16352
0
    IM_ASSERT(node->Windows.Size >= 1);
16353
16354
0
    if (node->IsRootNode() || node->IsCentralNode())
16355
0
    {
16356
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16357
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16358
0
        new_node->Pos = node->Pos;
16359
0
        new_node->Size = node->Size;
16360
0
        new_node->SizeRef = node->SizeRef;
16361
0
        DockNodeMoveWindows(new_node, node);
16362
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16363
0
        node = new_node;
16364
0
    }
16365
0
    else
16366
0
    {
16367
        // Otherwise extract our node and merge our sibling back into the parent node.
16368
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16369
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16370
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16371
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16372
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16373
0
        node->ParentNode = NULL;
16374
0
    }
16375
0
    for (ImGuiWindow* window : node->Windows)
16376
0
    {
16377
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16378
0
        if (window->ParentWindow)
16379
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16380
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16381
0
    }
16382
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16383
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16384
0
    node->WantMouseMove = true;
16385
0
    MarkIniSettingsDirty();
16386
0
}
16387
16388
// This is mostly used for automation.
16389
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16390
0
{
16391
0
    if (target != NULL && target_node == NULL)
16392
0
        target_node = target->DockNode;
16393
16394
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16395
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16396
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16397
0
        split_outer = true;
16398
0
    ImGuiDockPreviewData split_data;
16399
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16400
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16401
0
        return false;
16402
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16403
0
    return true;
16404
0
}
16405
16406
//-----------------------------------------------------------------------------
16407
// Docking: ImGuiDockNode
16408
//-----------------------------------------------------------------------------
16409
// - DockNodeGetTabOrder()
16410
// - DockNodeAddWindow()
16411
// - DockNodeRemoveWindow()
16412
// - DockNodeMoveChildNodes()
16413
// - DockNodeMoveWindows()
16414
// - DockNodeApplyPosSizeToWindows()
16415
// - DockNodeHideHostWindow()
16416
// - ImGuiDockNodeFindInfoResults
16417
// - DockNodeFindInfo()
16418
// - DockNodeFindWindowByID()
16419
// - DockNodeUpdateFlagsAndCollapse()
16420
// - DockNodeUpdateHasCentralNodeFlag()
16421
// - DockNodeUpdateVisibleFlag()
16422
// - DockNodeStartMouseMovingWindow()
16423
// - DockNodeUpdate()
16424
// - DockNodeUpdateWindowMenu()
16425
// - DockNodeBeginAmendTabBar()
16426
// - DockNodeEndAmendTabBar()
16427
// - DockNodeUpdateTabBar()
16428
// - DockNodeAddTabBar()
16429
// - DockNodeRemoveTabBar()
16430
// - DockNodeIsDropAllowedOne()
16431
// - DockNodeIsDropAllowed()
16432
// - DockNodeCalcTabBarLayout()
16433
// - DockNodeCalcSplitRects()
16434
// - DockNodeCalcDropRectsAndTestMousePos()
16435
// - DockNodePreviewDockSetup()
16436
// - DockNodePreviewDockRender()
16437
//-----------------------------------------------------------------------------
16438
16439
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16440
0
{
16441
0
    ID = id;
16442
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16443
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16444
0
    TabBar = NULL;
16445
0
    SplitAxis = ImGuiAxis_None;
16446
16447
0
    State = ImGuiDockNodeState_Unknown;
16448
0
    LastBgColor = IM_COL32_WHITE;
16449
0
    HostWindow = VisibleWindow = NULL;
16450
0
    CentralNode = OnlyNodeWithWindows = NULL;
16451
0
    CountNodeWithWindows = 0;
16452
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16453
0
    LastFocusedNodeId = 0;
16454
0
    SelectedTabId = 0;
16455
0
    WantCloseTabId = 0;
16456
0
    RefViewportId = 0;
16457
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16458
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16459
0
    IsVisible = true;
16460
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16461
0
    IsBgDrawnThisFrame = false;
16462
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16463
0
}
16464
16465
ImGuiDockNode::~ImGuiDockNode()
16466
0
{
16467
0
    IM_DELETE(TabBar);
16468
0
    TabBar = NULL;
16469
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16470
0
}
16471
16472
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16473
0
{
16474
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16475
0
    if (tab_bar == NULL)
16476
0
        return -1;
16477
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16478
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16479
0
}
16480
16481
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16482
0
{
16483
0
    window->Hidden = true;
16484
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16485
0
}
16486
16487
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16488
0
{
16489
0
    ImGuiContext& g = *GImGui; (void)g;
16490
0
    if (window->DockNode)
16491
0
    {
16492
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16493
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16494
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16495
0
    }
16496
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16497
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16498
16499
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16500
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16501
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16502
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16503
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16504
16505
0
    node->Windows.push_back(window);
16506
0
    node->WantHiddenTabBarUpdate = true;
16507
0
    window->DockNode = node;
16508
0
    window->DockId = node->ID;
16509
0
    window->DockIsActive = (node->Windows.Size > 1);
16510
0
    window->DockTabWantClose = false;
16511
16512
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16513
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16514
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16515
0
    {
16516
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16517
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16518
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16519
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16520
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16521
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16522
0
    }
16523
16524
    // Add to tab bar if requested
16525
0
    if (add_to_tab_bar)
16526
0
    {
16527
0
        if (node->TabBar == NULL)
16528
0
        {
16529
0
            DockNodeAddTabBar(node);
16530
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16531
16532
            // Add existing windows
16533
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16534
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16535
0
        }
16536
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16537
0
    }
16538
16539
0
    DockNodeUpdateVisibleFlag(node);
16540
16541
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16542
0
    if (node->HostWindow)
16543
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16544
0
}
16545
16546
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16547
0
{
16548
0
    ImGuiContext& g = *GImGui;
16549
0
    IM_ASSERT(window->DockNode == node);
16550
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16551
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16552
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16553
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16554
16555
0
    window->DockNode = NULL;
16556
0
    window->DockIsActive = window->DockTabWantClose = false;
16557
0
    window->DockId = save_dock_id;
16558
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16559
0
    if (window->ParentWindow)
16560
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16561
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16562
16563
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16564
0
    {
16565
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16566
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16567
0
        window->Viewport = NULL;
16568
0
        window->ViewportId = 0;
16569
0
        window->ViewportOwned = false;
16570
0
        window->Hidden = true;
16571
0
    }
16572
16573
    // Remove window
16574
0
    bool erased = false;
16575
0
    for (int n = 0; n < node->Windows.Size; n++)
16576
0
        if (node->Windows[n] == window)
16577
0
        {
16578
0
            node->Windows.erase(node->Windows.Data + n);
16579
0
            erased = true;
16580
0
            break;
16581
0
        }
16582
0
    if (!erased)
16583
0
        IM_ASSERT(erased);
16584
0
    if (node->VisibleWindow == window)
16585
0
        node->VisibleWindow = NULL;
16586
16587
    // Remove tab and possibly tab bar
16588
0
    node->WantHiddenTabBarUpdate = true;
16589
0
    if (node->TabBar)
16590
0
    {
16591
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16592
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16593
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16594
0
            DockNodeRemoveTabBar(node);
16595
0
    }
16596
16597
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16598
0
    {
16599
        // Automatic dock node delete themselves if they are not holding at least one tab
16600
0
        DockContextRemoveNode(&g, node, true);
16601
0
        return;
16602
0
    }
16603
16604
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16605
0
    {
16606
0
        ImGuiWindow* remaining_window = node->Windows[0];
16607
        // Note: we used to transport viewport ownership here.
16608
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16609
0
    }
16610
16611
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16612
0
    DockNodeUpdateVisibleFlag(node);
16613
0
}
16614
16615
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16616
0
{
16617
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16618
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16619
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16620
0
    if (dst_node->ChildNodes[0])
16621
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16622
0
    if (dst_node->ChildNodes[1])
16623
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16624
0
    dst_node->SplitAxis = src_node->SplitAxis;
16625
0
    dst_node->SizeRef = src_node->SizeRef;
16626
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16627
0
}
16628
16629
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16630
0
{
16631
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16632
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16633
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16634
0
    if (src_tab_bar != NULL)
16635
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16636
16637
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16638
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16639
0
    if (move_tab_bar)
16640
0
    {
16641
0
        dst_node->TabBar = src_node->TabBar;
16642
0
        src_node->TabBar = NULL;
16643
0
    }
16644
16645
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16646
0
    for (ImGuiWindow* window : src_node->Windows)
16647
0
    {
16648
0
        window->DockNode = NULL;
16649
0
        window->DockIsActive = false;
16650
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16651
0
    }
16652
0
    src_node->Windows.clear();
16653
16654
0
    if (!move_tab_bar && src_node->TabBar)
16655
0
    {
16656
0
        if (dst_node->TabBar)
16657
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16658
0
        DockNodeRemoveTabBar(src_node);
16659
0
    }
16660
0
}
16661
16662
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16663
0
{
16664
0
    for (ImGuiWindow* window : node->Windows)
16665
0
    {
16666
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16667
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16668
0
    }
16669
0
}
16670
16671
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16672
0
{
16673
0
    if (node->HostWindow)
16674
0
    {
16675
0
        if (node->HostWindow->DockNodeAsHost == node)
16676
0
            node->HostWindow->DockNodeAsHost = NULL;
16677
0
        node->HostWindow = NULL;
16678
0
    }
16679
16680
0
    if (node->Windows.Size == 1)
16681
0
    {
16682
0
        node->VisibleWindow = node->Windows[0];
16683
0
        node->Windows[0]->DockIsActive = false;
16684
0
    }
16685
16686
0
    if (node->TabBar)
16687
0
        DockNodeRemoveTabBar(node);
16688
0
}
16689
16690
// Search function called once by root node in DockNodeUpdate()
16691
struct ImGuiDockNodeTreeInfo
16692
{
16693
    ImGuiDockNode*      CentralNode;
16694
    ImGuiDockNode*      FirstNodeWithWindows;
16695
    int                 CountNodesWithWindows;
16696
    //ImGuiWindowClass  WindowClassForMerges;
16697
16698
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16699
};
16700
16701
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16702
0
{
16703
0
    if (node->Windows.Size > 0)
16704
0
    {
16705
0
        if (info->FirstNodeWithWindows == NULL)
16706
0
            info->FirstNodeWithWindows = node;
16707
0
        info->CountNodesWithWindows++;
16708
0
    }
16709
0
    if (node->IsCentralNode())
16710
0
    {
16711
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16712
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16713
0
        info->CentralNode = node;
16714
0
    }
16715
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16716
0
        return;
16717
0
    if (node->ChildNodes[0])
16718
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16719
0
    if (node->ChildNodes[1])
16720
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16721
0
}
16722
16723
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16724
0
{
16725
0
    IM_ASSERT(id != 0);
16726
0
    for (ImGuiWindow* window : node->Windows)
16727
0
        if (window->ID == id)
16728
0
            return window;
16729
0
    return NULL;
16730
0
}
16731
16732
// - Remove inactive windows/nodes.
16733
// - Update visibility flag.
16734
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16735
0
{
16736
0
    ImGuiContext& g = *GImGui;
16737
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16738
16739
    // Inherit most flags
16740
0
    if (node->ParentNode)
16741
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16742
16743
    // Recurse into children
16744
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16745
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16746
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16747
0
    node->HasCentralNodeChild = false;
16748
0
    if (node->ChildNodes[0])
16749
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16750
0
    if (node->ChildNodes[1])
16751
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16752
16753
    // Remove inactive windows, collapse nodes
16754
    // Merge node flags overrides stored in windows
16755
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16756
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16757
0
    {
16758
0
        ImGuiWindow* window = node->Windows[window_n];
16759
0
        IM_ASSERT(window->DockNode == node);
16760
16761
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16762
0
        bool remove = false;
16763
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16764
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16765
0
        remove |= (window->DockTabWantClose);
16766
0
        if (remove)
16767
0
        {
16768
0
            window->DockTabWantClose = false;
16769
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16770
0
            {
16771
0
                DockNodeHideHostWindow(node);
16772
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16773
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16774
0
                return;
16775
0
            }
16776
0
            DockNodeRemoveWindow(node, window, node->ID);
16777
0
            window_n--;
16778
0
            continue;
16779
0
        }
16780
16781
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16782
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16783
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16784
0
    }
16785
0
    node->UpdateMergedFlags();
16786
16787
    // Auto-hide tab bar option
16788
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16789
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16790
0
        node->WantHiddenTabBarToggle = true;
16791
0
    node->WantHiddenTabBarUpdate = false;
16792
16793
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16794
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16795
0
        node->WantHiddenTabBarToggle = false;
16796
16797
    // Apply toggles at a single point of the frame (here!)
16798
0
    if (node->Windows.Size > 1)
16799
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16800
0
    else if (node->WantHiddenTabBarToggle)
16801
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16802
0
    node->WantHiddenTabBarToggle = false;
16803
16804
0
    DockNodeUpdateVisibleFlag(node);
16805
0
}
16806
16807
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16808
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16809
0
{
16810
0
    node->HasCentralNodeChild = false;
16811
0
    if (node->ChildNodes[0])
16812
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16813
0
    if (node->ChildNodes[1])
16814
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16815
0
    if (node->IsRootNode())
16816
0
    {
16817
0
        ImGuiDockNode* mark_node = node->CentralNode;
16818
0
        while (mark_node)
16819
0
        {
16820
0
            mark_node->HasCentralNodeChild = true;
16821
0
            mark_node = mark_node->ParentNode;
16822
0
        }
16823
0
    }
16824
0
}
16825
16826
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16827
0
{
16828
    // Update visibility flag
16829
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16830
0
    is_visible |= (node->Windows.Size > 0);
16831
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16832
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16833
0
    node->IsVisible = is_visible;
16834
0
}
16835
16836
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16837
0
{
16838
0
    ImGuiContext& g = *GImGui;
16839
0
    IM_ASSERT(node->WantMouseMove == true);
16840
0
    StartMouseMovingWindow(window);
16841
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16842
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16843
0
    node->WantMouseMove = false;
16844
0
}
16845
16846
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16847
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16848
0
{
16849
0
    DockNodeUpdateFlagsAndCollapse(node);
16850
16851
    // - Setup central node pointers
16852
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16853
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16854
0
    ImGuiDockNodeTreeInfo info;
16855
0
    DockNodeFindInfo(node, &info);
16856
0
    node->CentralNode = info.CentralNode;
16857
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16858
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16859
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16860
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16861
16862
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16863
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16864
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16865
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16866
0
    {
16867
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16868
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16869
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16870
0
            {
16871
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16872
0
                break;
16873
0
            }
16874
0
    }
16875
16876
0
    ImGuiDockNode* mark_node = node->CentralNode;
16877
0
    while (mark_node)
16878
0
    {
16879
0
        mark_node->HasCentralNodeChild = true;
16880
0
        mark_node = mark_node->ParentNode;
16881
0
    }
16882
0
}
16883
16884
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16885
0
{
16886
    // Remove ourselves from any previous different host window
16887
    // This can happen if a user mistakenly does (see #4295 for details):
16888
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16889
    //  - N+1: NewFrame()                   // will create floating host window for that node
16890
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16891
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16892
0
        node->HostWindow->DockNodeAsHost = NULL;
16893
16894
0
    host_window->DockNodeAsHost = node;
16895
0
    node->HostWindow = host_window;
16896
0
}
16897
16898
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16899
0
{
16900
0
    ImGuiContext& g = *GImGui;
16901
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16902
0
    node->LastFrameAlive = g.FrameCount;
16903
0
    node->IsBgDrawnThisFrame = false;
16904
16905
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16906
0
    if (node->IsRootNode())
16907
0
        DockNodeUpdateForRootNode(node);
16908
16909
    // Remove tab bar if not needed
16910
0
    if (node->TabBar && node->IsNoTabBar())
16911
0
        DockNodeRemoveTabBar(node);
16912
16913
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16914
0
    bool want_to_hide_host_window = false;
16915
0
    if (node->IsFloatingNode())
16916
0
    {
16917
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16918
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16919
0
                want_to_hide_host_window = true;
16920
0
        if (node->CountNodeWithWindows == 0)
16921
0
            want_to_hide_host_window = true;
16922
0
    }
16923
0
    if (want_to_hide_host_window)
16924
0
    {
16925
0
        if (node->Windows.Size == 1)
16926
0
        {
16927
            // Floating window pos/size is authoritative
16928
0
            ImGuiWindow* single_window = node->Windows[0];
16929
0
            node->Pos = single_window->Pos;
16930
0
            node->Size = single_window->SizeFull;
16931
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16932
16933
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16934
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16935
0
                FocusWindow(single_window);
16936
0
            if (node->HostWindow)
16937
0
            {
16938
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16939
0
                single_window->Viewport = node->HostWindow->Viewport;
16940
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16941
0
                if (node->HostWindow->ViewportOwned)
16942
0
                {
16943
0
                    single_window->Viewport->ID = single_window->ID;
16944
0
                    single_window->Viewport->Window = single_window;
16945
0
                    single_window->ViewportOwned = true;
16946
0
                }
16947
0
            }
16948
0
            node->RefViewportId = single_window->ViewportId;
16949
0
        }
16950
16951
0
        DockNodeHideHostWindow(node);
16952
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16953
0
        node->WantCloseAll = false;
16954
0
        node->WantCloseTabId = 0;
16955
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16956
0
        node->LastFrameActive = g.FrameCount;
16957
16958
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16959
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16960
0
        return;
16961
0
    }
16962
16963
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16964
    // while the expected visible window is resizing itself.
16965
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16966
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16967
    //   N+0: Begin(): window created (with no known size), node is created
16968
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16969
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16970
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16971
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16972
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16973
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16974
0
    {
16975
0
        IM_ASSERT(node->Windows.Size > 0);
16976
0
        ImGuiWindow* ref_window = NULL;
16977
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16978
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16979
0
        if (ref_window == NULL)
16980
0
            ref_window = node->Windows[0];
16981
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16982
0
        {
16983
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16984
0
            return;
16985
0
        }
16986
0
    }
16987
16988
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16989
16990
    // Decide if the node will have a close button and a window menu button
16991
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16992
0
    node->HasCloseButton = false;
16993
0
    for (ImGuiWindow* window : node->Windows)
16994
0
    {
16995
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16996
0
        node->HasCloseButton |= window->HasCloseButton;
16997
0
        window->DockIsActive = (node->Windows.Size > 1);
16998
0
    }
16999
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
17000
0
        node->HasCloseButton = false;
17001
17002
    // Bind or create host window
17003
0
    ImGuiWindow* host_window = NULL;
17004
0
    bool beginned_into_host_window = false;
17005
0
    if (node->IsDockSpace())
17006
0
    {
17007
        // [Explicit root dockspace node]
17008
0
        IM_ASSERT(node->HostWindow);
17009
0
        host_window = node->HostWindow;
17010
0
    }
17011
0
    else
17012
0
    {
17013
        // [Automatic root or child nodes]
17014
0
        if (node->IsRootNode() && node->IsVisible)
17015
0
        {
17016
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17017
17018
            // Sync Pos
17019
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
17020
0
                SetNextWindowPos(ref_window->Pos);
17021
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
17022
0
                SetNextWindowPos(node->Pos);
17023
17024
            // Sync Size
17025
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17026
0
                SetNextWindowSize(ref_window->SizeFull);
17027
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17028
0
                SetNextWindowSize(node->Size);
17029
17030
            // Sync Collapsed
17031
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17032
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17033
17034
            // Sync Viewport
17035
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17036
0
                SetNextWindowViewport(ref_window->ViewportId);
17037
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17038
0
                SetNextWindowViewport(node->RefViewportId);
17039
17040
0
            SetNextWindowClass(&node->WindowClass);
17041
17042
            // Begin into the host window
17043
0
            char window_label[20];
17044
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17045
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17046
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17047
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17048
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17049
17050
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17051
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17052
0
            Begin(window_label, NULL, window_flags);
17053
0
            PopStyleVar();
17054
0
            beginned_into_host_window = true;
17055
17056
0
            host_window = g.CurrentWindow;
17057
0
            DockNodeSetupHostWindow(node, host_window);
17058
0
            host_window->DC.CursorPos = host_window->Pos;
17059
0
            node->Pos = host_window->Pos;
17060
0
            node->Size = host_window->Size;
17061
17062
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17063
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17064
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17065
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17066
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17067
            // after the dock host window, losing their top-most status.
17068
0
            if (node->HostWindow->Appearing)
17069
0
                BringWindowToDisplayFront(node->HostWindow);
17070
17071
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17072
0
        }
17073
0
        else if (node->ParentNode)
17074
0
        {
17075
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17076
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17077
0
        }
17078
0
        if (node->WantMouseMove && node->HostWindow)
17079
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17080
0
    }
17081
0
    node->RefViewportId = 0; // Clear when we have a host window
17082
17083
    // Update focused node (the one whose title bar is highlight) within a node tree
17084
0
    if (node->IsSplitNode())
17085
0
        IM_ASSERT(node->TabBar == NULL);
17086
0
    if (node->IsRootNode())
17087
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17088
0
            while (p_window != NULL && p_window->DockNode != NULL)
17089
0
            {
17090
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17091
0
                if (p_node == node)
17092
0
                {
17093
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17094
0
                    break;
17095
0
                }
17096
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17097
0
            }
17098
17099
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17100
0
    ImGuiDockNode* central_node = node->CentralNode;
17101
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17102
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17103
0
    if (central_node_hole)
17104
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17105
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17106
0
                central_node_hole_register_hit_test_hole = false;
17107
0
    if (central_node_hole_register_hit_test_hole)
17108
0
    {
17109
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17110
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17111
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17112
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17113
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17114
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17115
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17116
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17117
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17118
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17119
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17120
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17121
0
        if (central_node_hole && !hole_rect.IsInverted())
17122
0
        {
17123
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17124
0
            if (host_window->ParentWindow)
17125
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17126
0
        }
17127
0
    }
17128
17129
    // Update position/size, process and draw resizing splitters
17130
0
    if (node->IsRootNode() && host_window)
17131
0
    {
17132
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17133
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17134
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17135
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17136
0
        DockNodeTreeUpdateSplitter(node);
17137
0
        PopStyleColor(3);
17138
0
    }
17139
17140
    // Draw empty node background (currently can only be the Central Node)
17141
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17142
0
    {
17143
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17144
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17145
0
        if (node->LastBgColor != 0)
17146
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17147
0
        node->IsBgDrawnThisFrame = true;
17148
0
    }
17149
17150
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17151
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17152
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17153
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17154
0
    if (render_dockspace_bg && node->IsVisible)
17155
0
    {
17156
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17157
0
        if (central_node_hole)
17158
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17159
0
        else
17160
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17161
0
    }
17162
17163
    // Draw and populate Tab Bar
17164
0
    if (host_window)
17165
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17166
0
    if (host_window && node->Windows.Size > 0)
17167
0
    {
17168
0
        DockNodeUpdateTabBar(node, host_window);
17169
0
    }
17170
0
    else
17171
0
    {
17172
0
        node->WantCloseAll = false;
17173
0
        node->WantCloseTabId = 0;
17174
0
        node->IsFocused = false;
17175
0
    }
17176
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17177
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17178
0
    else if (node->Windows.Size > 0)
17179
0
        node->SelectedTabId = node->Windows[0]->TabId;
17180
17181
    // Draw payload drop target
17182
0
    if (host_window && node->IsVisible)
17183
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17184
0
            BeginDockableDragDropTarget(host_window);
17185
17186
    // We update this after DockNodeUpdateTabBar()
17187
0
    node->LastFrameActive = g.FrameCount;
17188
17189
    // Recurse into children
17190
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17191
0
    if (host_window)
17192
0
    {
17193
0
        if (node->ChildNodes[0])
17194
0
            DockNodeUpdate(node->ChildNodes[0]);
17195
0
        if (node->ChildNodes[1])
17196
0
            DockNodeUpdate(node->ChildNodes[1]);
17197
17198
        // Render outer borders last (after the tab bar)
17199
0
        if (node->IsRootNode())
17200
0
            RenderWindowOuterBorders(host_window);
17201
0
    }
17202
17203
    // End host window
17204
0
    if (beginned_into_host_window) //-V1020
17205
0
        End();
17206
0
}
17207
17208
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17209
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17210
0
{
17211
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17212
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17213
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17214
0
        return d;
17215
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17216
0
}
17217
17218
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17219
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17220
// Custom overrides may want to decorate, group, sort entries.
17221
// Please note those are internal structures: if you copy this expect occasional breakage.
17222
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17223
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17224
0
{
17225
0
    IM_UNUSED(ctx);
17226
0
    if (tab_bar->Tabs.Size == 1)
17227
0
    {
17228
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17229
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17230
0
            node->WantHiddenTabBarToggle = true;
17231
0
    }
17232
0
    else
17233
0
    {
17234
        // Display a selectable list of windows in this docking node
17235
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17236
0
        {
17237
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17238
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17239
0
                continue;
17240
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17241
0
                TabBarQueueFocus(tab_bar, tab);
17242
0
            SameLine();
17243
0
            Text("   ");
17244
0
        }
17245
0
    }
17246
0
}
17247
17248
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17249
0
{
17250
    // Try to position the menu so it is more likely to stays within the same viewport
17251
0
    ImGuiContext& g = *GImGui;
17252
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17253
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17254
0
    else
17255
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17256
0
    if (BeginPopup("#WindowMenu"))
17257
0
    {
17258
0
        node->IsFocused = true;
17259
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17260
0
        EndPopup();
17261
0
    }
17262
0
}
17263
17264
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17265
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17266
0
{
17267
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17268
0
        return false;
17269
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17270
0
        return false;
17271
0
    if (node->TabBar->ID == 0)
17272
0
        return false;
17273
0
    Begin(node->HostWindow->Name);
17274
0
    PushOverrideID(node->ID);
17275
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17276
0
    IM_UNUSED(ret);
17277
0
    IM_ASSERT(ret);
17278
0
    return true;
17279
0
}
17280
17281
void ImGui::DockNodeEndAmendTabBar()
17282
0
{
17283
0
    EndTabBar();
17284
0
    PopID();
17285
0
    End();
17286
0
}
17287
17288
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17289
0
{
17290
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17291
0
    ImGuiContext& g = *GImGui;
17292
0
    if (g.NavWindowingTarget)
17293
0
        return (g.NavWindowingTarget->DockNode == node);
17294
17295
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17296
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17297
0
    {
17298
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17299
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17300
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17301
0
            parent_window = parent_window->ParentWindow->RootWindow;
17302
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17303
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17304
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17305
0
                return true;
17306
0
    }
17307
0
    return false;
17308
0
}
17309
17310
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17311
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17312
0
{
17313
0
    ImGuiContext& g = *GImGui;
17314
0
    ImGuiStyle& style = g.Style;
17315
17316
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17317
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17318
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17319
0
    node->WantCloseAll = false;
17320
0
    node->WantCloseTabId = 0;
17321
17322
    // Decide if we should use a focused title bar color
17323
0
    bool is_focused = false;
17324
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17325
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17326
0
        is_focused = true;
17327
17328
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17329
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17330
0
    {
17331
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17332
0
        node->IsFocused = is_focused;
17333
0
        if (is_focused)
17334
0
            node->LastFrameFocused = g.FrameCount;
17335
0
        if (node->VisibleWindow)
17336
0
        {
17337
            // Notify root of visible window (used to display title in OS task bar)
17338
0
            if (is_focused || root_node->VisibleWindow == NULL)
17339
0
                root_node->VisibleWindow = node->VisibleWindow;
17340
0
            if (node->TabBar)
17341
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17342
0
        }
17343
0
        return;
17344
0
    }
17345
17346
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17347
0
    bool backup_skip_item = host_window->SkipItems;
17348
0
    if (!node->IsDockSpace())
17349
0
    {
17350
0
        host_window->SkipItems = false;
17351
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17352
0
    }
17353
17354
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17355
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17356
    // as docked windows themselves will override the stack with their own root ID.
17357
0
    PushOverrideID(node->ID);
17358
0
    ImGuiTabBar* tab_bar = node->TabBar;
17359
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17360
0
    if (tab_bar == NULL)
17361
0
    {
17362
0
        DockNodeAddTabBar(node);
17363
0
        tab_bar = node->TabBar;
17364
0
    }
17365
17366
0
    ImGuiID focus_tab_id = 0;
17367
0
    node->IsFocused = is_focused;
17368
17369
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17370
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17371
17372
    // In a dock node, the Collapse Button turns into the Window Menu button.
17373
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17374
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17375
0
    {
17376
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17377
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17378
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17379
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17380
0
        is_focused |= node->IsFocused;
17381
0
    }
17382
17383
    // Layout
17384
0
    ImRect title_bar_rect, tab_bar_rect;
17385
0
    ImVec2 window_menu_button_pos;
17386
0
    ImVec2 close_button_pos;
17387
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17388
17389
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17390
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17391
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17392
0
    {
17393
0
        ImGuiWindow* window = node->Windows[window_n];
17394
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17395
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17396
0
    }
17397
17398
    // Title bar
17399
0
    if (is_focused)
17400
0
        node->LastFrameFocused = g.FrameCount;
17401
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17402
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17403
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17404
17405
    // Docking/Collapse button
17406
0
    if (has_window_menu_button)
17407
0
    {
17408
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17409
0
            OpenPopup("#WindowMenu");
17410
0
        if (IsItemActive())
17411
0
            focus_tab_id = tab_bar->SelectedTabId;
17412
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17413
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17414
0
    }
17415
17416
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17417
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17418
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17419
0
    {
17420
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17421
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17422
0
        tabs_unsorted_start = tab_n;
17423
0
    }
17424
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17425
0
    {
17426
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17427
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17428
0
        {
17429
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17430
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17431
0
        }
17432
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17433
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17434
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17435
0
    }
17436
17437
    // Apply NavWindow focus back to the tab bar
17438
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17439
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17440
17441
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17442
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17443
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17444
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17445
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17446
17447
    // Begin tab bar
17448
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17449
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17450
0
    if (!host_window->Collapsed && is_focused)
17451
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17452
0
    tab_bar->ID = GetID("#TabBar");
17453
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17454
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17455
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17456
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17457
17458
    // Backup style colors
17459
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17460
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17461
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17462
17463
    // Submit actual tabs
17464
0
    node->VisibleWindow = NULL;
17465
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17466
0
    {
17467
0
        ImGuiWindow* window = node->Windows[window_n];
17468
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17469
0
            continue;
17470
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17471
0
        {
17472
0
            ImGuiTabItemFlags tab_item_flags = 0;
17473
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17474
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17475
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17476
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17477
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17478
17479
            // Apply stored style overrides for the window
17480
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17481
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17482
17483
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17484
0
            bool tab_open = true;
17485
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17486
0
            if (!tab_open)
17487
0
                node->WantCloseTabId = window->TabId;
17488
0
            if (tab_bar->VisibleTabId == window->TabId)
17489
0
                node->VisibleWindow = window;
17490
17491
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17492
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17493
0
            window->DockTabItemRect = g.LastItemData.Rect;
17494
17495
            // Update navigation ID on menu layer
17496
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17497
0
                host_window->NavLastIds[1] = window->TabId;
17498
0
        }
17499
0
    }
17500
17501
    // Restore style colors
17502
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17503
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17504
17505
    // Notify root of visible window (used to display title in OS task bar)
17506
0
    if (node->VisibleWindow)
17507
0
        if (is_focused || root_node->VisibleWindow == NULL)
17508
0
            root_node->VisibleWindow = node->VisibleWindow;
17509
17510
    // Close button (after VisibleWindow was updated)
17511
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17512
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17513
0
    const bool close_button_is_visible = node->HasCloseButton;
17514
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17515
0
    if (close_button_is_visible)
17516
0
    {
17517
0
        if (!close_button_is_enabled)
17518
0
        {
17519
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17520
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17521
0
        }
17522
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17523
0
        {
17524
0
            node->WantCloseAll = true;
17525
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17526
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17527
0
        }
17528
        //if (IsItemActive())
17529
        //    focus_tab_id = tab_bar->SelectedTabId;
17530
0
        if (!close_button_is_enabled)
17531
0
        {
17532
0
            PopStyleColor();
17533
0
            PopItemFlag();
17534
0
        }
17535
0
    }
17536
17537
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17538
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17539
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17540
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17541
0
    {
17542
        // AllowOverlap mode required for appending into dock node tab bar,
17543
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17544
0
        bool held;
17545
0
        KeepAliveID(title_bar_id);
17546
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17547
0
        if (g.HoveredId == title_bar_id)
17548
0
        {
17549
0
            g.LastItemData.ID = title_bar_id;
17550
0
        }
17551
0
        if (held)
17552
0
        {
17553
0
            if (IsMouseClicked(0))
17554
0
                focus_tab_id = tab_bar->SelectedTabId;
17555
17556
            // Forward moving request to selected window
17557
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17558
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17559
0
        }
17560
0
    }
17561
17562
    // Forward focus from host node to selected window
17563
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17564
    //    focus_tab_id = tab_bar->SelectedTabId;
17565
17566
    // When clicked on a tab we requested focus to the docked child
17567
    // This overrides the value set by "forward focus from host node to selected window".
17568
0
    if (tab_bar->NextSelectedTabId)
17569
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17570
17571
    // Apply navigation focus
17572
0
    if (focus_tab_id != 0)
17573
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17574
0
            if (tab->Window)
17575
0
            {
17576
0
                FocusWindow(tab->Window);
17577
0
                NavInitWindow(tab->Window, false);
17578
0
            }
17579
17580
0
    EndTabBar();
17581
0
    PopID();
17582
17583
    // Restore SkipItems flag
17584
0
    if (!node->IsDockSpace())
17585
0
    {
17586
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17587
0
        host_window->SkipItems = backup_skip_item;
17588
0
    }
17589
0
}
17590
17591
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17592
0
{
17593
0
    IM_ASSERT(node->TabBar == NULL);
17594
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17595
0
}
17596
17597
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17598
0
{
17599
0
    if (node->TabBar == NULL)
17600
0
        return;
17601
0
    IM_DELETE(node->TabBar);
17602
0
    node->TabBar = NULL;
17603
0
}
17604
17605
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17606
0
{
17607
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17608
0
        return false;
17609
17610
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17611
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17612
0
    if (host_class->ClassId != payload_class->ClassId)
17613
0
    {
17614
0
        bool pass = false;
17615
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17616
0
            pass = true;
17617
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17618
0
            pass = true;
17619
0
        if (!pass)
17620
0
            return false;
17621
0
    }
17622
17623
    // Prevent docking any window created above a popup
17624
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17625
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17626
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17627
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17628
0
    ImGuiContext& g = *GImGui;
17629
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17630
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17631
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17632
0
                return false;
17633
17634
0
    return true;
17635
0
}
17636
17637
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17638
0
{
17639
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17640
0
        return true;
17641
17642
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17643
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17644
0
    {
17645
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17646
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
17647
0
            return true;
17648
0
    }
17649
0
    return false;
17650
0
}
17651
17652
// window menu button == collapse button when not in a dock node.
17653
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17654
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17655
0
{
17656
0
    ImGuiContext& g = *GImGui;
17657
0
    ImGuiStyle& style = g.Style;
17658
17659
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17660
0
    if (out_title_rect) { *out_title_rect = r; }
17661
17662
0
    r.Min.x += style.WindowBorderSize;
17663
0
    r.Max.x -= style.WindowBorderSize;
17664
17665
0
    float button_sz = g.FontSize;
17666
0
    r.Min.x += style.FramePadding.x;
17667
0
    r.Max.x -= style.FramePadding.x;
17668
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17669
0
    if (node->HasCloseButton)
17670
0
    {
17671
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17672
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17673
0
    }
17674
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17675
0
    {
17676
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17677
0
    }
17678
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17679
0
    {
17680
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17681
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17682
0
    }
17683
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17684
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17685
0
}
17686
17687
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17688
0
{
17689
0
    ImGuiContext& g = *GImGui;
17690
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17691
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17692
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17693
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17694
17695
    // Distribute size on given axis (with a desired size or equally)
17696
0
    const float w_avail = size_old[axis] - dock_spacing;
17697
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17698
0
    {
17699
0
        size_new[axis] = size_new_desired[axis];
17700
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17701
0
    }
17702
0
    else
17703
0
    {
17704
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17705
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17706
0
    }
17707
17708
    // Position each node
17709
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17710
0
    {
17711
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17712
0
    }
17713
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17714
0
    {
17715
0
        pos_new[axis] = pos_old[axis];
17716
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17717
0
    }
17718
0
}
17719
17720
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17721
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17722
0
{
17723
0
    ImGuiContext& g = *GImGui;
17724
17725
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17726
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17727
0
    float hs_w; // Half-size, longer axis
17728
0
    float hs_h; // Half-size, smaller axis
17729
0
    ImVec2 off; // Distance from edge or center
17730
0
    if (outer_docking)
17731
0
    {
17732
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17733
        //hs_h = ImTrunc(hs_w * 0.15f);
17734
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17735
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17736
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17737
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17738
0
    }
17739
0
    else
17740
0
    {
17741
0
        hs_w = ImTrunc(hs_for_central_nodes);
17742
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17743
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17744
0
    }
17745
17746
0
    ImVec2 c = ImTrunc(parent.GetCenter());
17747
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17748
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17749
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17750
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17751
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17752
17753
0
    if (test_mouse_pos == NULL)
17754
0
        return false;
17755
17756
0
    ImRect hit_r = out_r;
17757
0
    if (!outer_docking)
17758
0
    {
17759
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17760
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
17761
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17762
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17763
0
        float r_threshold_center = hs_w * 1.4f;
17764
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17765
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17766
0
            return (dir == ImGuiDir_None);
17767
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17768
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17769
0
    }
17770
0
    return hit_r.Contains(*test_mouse_pos);
17771
0
}
17772
17773
// host_node may be NULL if the window doesn't have a DockNode already.
17774
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17775
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17776
0
{
17777
0
    ImGuiContext& g = *GImGui;
17778
17779
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17780
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17781
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17782
0
    if (payload_node == NULL)
17783
0
        payload_node = payload_window->DockNodeAsHost;
17784
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17785
0
    if (ref_node_for_rect)
17786
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17787
17788
    // Filter, figure out where we are allowed to dock
17789
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17790
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17791
0
    data->IsCenterAvailable = true;
17792
0
    if (is_outer_docking)
17793
0
        data->IsCenterAvailable = false;
17794
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17795
0
        data->IsCenterAvailable = false;
17796
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17797
0
        data->IsCenterAvailable = false;
17798
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17799
0
        data->IsCenterAvailable = false;
17800
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17801
0
        data->IsCenterAvailable = false;
17802
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17803
0
        data->IsCenterAvailable = false;
17804
17805
0
    data->IsSidesAvailable = true;
17806
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17807
0
        data->IsSidesAvailable = false;
17808
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17809
0
        data->IsSidesAvailable = false;
17810
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17811
0
        data->IsSidesAvailable = false;
17812
17813
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17814
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17815
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17816
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17817
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17818
17819
    // Calculate drop shapes geometry for allowed splitting directions
17820
0
    IM_ASSERT(ImGuiDir_None == -1);
17821
0
    data->SplitNode = host_node;
17822
0
    data->SplitDir = ImGuiDir_None;
17823
0
    data->IsSplitDirExplicit = false;
17824
0
    if (!host_window->Collapsed)
17825
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17826
0
        {
17827
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17828
0
                continue;
17829
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17830
0
                continue;
17831
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17832
0
            {
17833
0
                data->SplitDir = (ImGuiDir)dir;
17834
0
                data->IsSplitDirExplicit = true;
17835
0
            }
17836
0
        }
17837
17838
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17839
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17840
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17841
0
        data->IsDropAllowed = false;
17842
17843
    // Calculate split area
17844
0
    data->SplitRatio = 0.0f;
17845
0
    if (data->SplitDir != ImGuiDir_None)
17846
0
    {
17847
0
        ImGuiDir split_dir = data->SplitDir;
17848
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17849
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17850
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17851
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17852
17853
        // Calculate split ratio so we can pass it down the docking request
17854
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17855
0
        data->FutureNode.Pos = pos_new;
17856
0
        data->FutureNode.Size = size_new;
17857
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17858
0
    }
17859
0
}
17860
17861
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17862
0
{
17863
0
    ImGuiContext& g = *GImGui;
17864
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17865
17866
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17867
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17868
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17869
17870
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17871
0
    int overlay_draw_lists_count = 0;
17872
0
    ImDrawList* overlay_draw_lists[2];
17873
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17874
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17875
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17876
17877
    // Draw main preview rectangle
17878
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17879
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17880
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17881
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17882
17883
    // Display area preview
17884
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17885
0
    if (data->IsDropAllowed)
17886
0
    {
17887
0
        ImRect overlay_rect = data->FutureNode.Rect();
17888
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17889
0
            overlay_rect.Min.y += GetFrameHeight();
17890
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17891
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17892
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17893
0
    }
17894
17895
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17896
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17897
0
    {
17898
        // Compute target tab bar geometry so we can locate our preview tabs
17899
0
        ImRect tab_bar_rect;
17900
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17901
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17902
0
        if (host_node && host_node->TabBar)
17903
0
        {
17904
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17905
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17906
0
            else
17907
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17908
0
        }
17909
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17910
0
        {
17911
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17912
0
        }
17913
17914
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17915
0
        if (root_payload->DockNodeAsHost)
17916
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17917
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17918
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17919
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17920
0
        {
17921
            // DockNode's TabBar may have non-window Tabs manually appended by user
17922
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17923
0
            if (tab_bar_with_payload && payload_window == NULL)
17924
0
                continue;
17925
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17926
0
                continue;
17927
17928
            // Calculate the tab bounding box for each payload window
17929
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17930
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17931
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17932
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17933
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17934
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17935
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17936
0
            {
17937
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17938
0
                if (!tab_bar_rect.Contains(tab_bb))
17939
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17940
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17941
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17942
0
                if (!tab_bar_rect.Contains(tab_bb))
17943
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17944
0
            }
17945
0
            PopStyleColor();
17946
0
        }
17947
0
    }
17948
17949
    // Display drop boxes
17950
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17951
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17952
0
    {
17953
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17954
0
        {
17955
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17956
0
            ImRect draw_r_in = draw_r;
17957
0
            draw_r_in.Expand(-2.0f);
17958
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17959
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17960
0
            {
17961
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17962
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17963
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17964
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17965
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17966
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17967
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17968
0
            }
17969
0
        }
17970
17971
        // Stop after ImGuiDir_None
17972
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17973
0
            return;
17974
0
    }
17975
0
}
17976
17977
//-----------------------------------------------------------------------------
17978
// Docking: ImGuiDockNode Tree manipulation functions
17979
//-----------------------------------------------------------------------------
17980
// - DockNodeTreeSplit()
17981
// - DockNodeTreeMerge()
17982
// - DockNodeTreeUpdatePosSize()
17983
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17984
// - DockNodeTreeUpdateSplitter()
17985
// - DockNodeTreeFindFallbackLeafNode()
17986
// - DockNodeTreeFindNodeByPos()
17987
//-----------------------------------------------------------------------------
17988
17989
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17990
0
{
17991
0
    ImGuiContext& g = *GImGui;
17992
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17993
17994
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17995
0
    child_0->ParentNode = parent_node;
17996
17997
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17998
0
    child_1->ParentNode = parent_node;
17999
18000
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
18001
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
18002
0
    parent_node->ChildNodes[0] = child_0;
18003
0
    parent_node->ChildNodes[1] = child_1;
18004
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
18005
0
    parent_node->SplitAxis = split_axis;
18006
0
    parent_node->VisibleWindow = NULL;
18007
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18008
18009
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
18010
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
18011
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
18012
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
18013
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
18014
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
18015
18016
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
18017
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
18018
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
18019
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
18020
18021
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
18022
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18023
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18024
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18025
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18026
0
    child_0->UpdateMergedFlags();
18027
0
    child_1->UpdateMergedFlags();
18028
0
    parent_node->UpdateMergedFlags();
18029
0
    if (child_inheritor->IsCentralNode())
18030
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18031
0
}
18032
18033
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18034
0
{
18035
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18036
0
    ImGuiContext& g = *GImGui;
18037
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18038
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18039
0
    IM_ASSERT(child_0 || child_1);
18040
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18041
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18042
0
    {
18043
0
        IM_ASSERT(parent_node->TabBar == NULL);
18044
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18045
0
    }
18046
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18047
18048
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18049
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18050
0
    if (child_0)
18051
0
    {
18052
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18053
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18054
0
    }
18055
0
    if (child_1)
18056
0
    {
18057
0
        DockNodeMoveWindows(parent_node, child_1);
18058
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18059
0
    }
18060
0
    DockNodeApplyPosSizeToWindows(parent_node);
18061
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18062
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18063
0
    parent_node->SizeRef = backup_last_explicit_size;
18064
18065
    // Flags transfer
18066
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18067
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18068
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18069
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18070
0
    parent_node->UpdateMergedFlags();
18071
18072
0
    if (child_0)
18073
0
    {
18074
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18075
0
        IM_DELETE(child_0);
18076
0
    }
18077
0
    if (child_1)
18078
0
    {
18079
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18080
0
        IM_DELETE(child_1);
18081
0
    }
18082
0
}
18083
18084
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18085
// (Depth-first, Pre-Order)
18086
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18087
0
{
18088
    // During the regular dock node update we write to all nodes.
18089
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18090
0
    ImGuiContext& g = *GImGui;
18091
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18092
0
    if (write_to_node)
18093
0
    {
18094
0
        node->Pos = pos;
18095
0
        node->Size = size;
18096
0
    }
18097
18098
0
    if (node->IsLeafNode())
18099
0
        return;
18100
18101
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18102
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18103
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18104
0
    ImVec2 child_0_size = size, child_1_size = size;
18105
18106
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18107
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18108
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18109
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18110
18111
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18112
0
    {
18113
0
        const float spacing = g.Style.DockingSeparatorSize;
18114
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18115
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18116
18117
        // Size allocation policy
18118
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18119
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18120
18121
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18122
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18123
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18124
18125
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18126
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18127
0
        {
18128
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18129
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18130
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18131
0
        }
18132
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18133
0
        {
18134
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18135
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18136
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18137
0
        }
18138
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18139
0
        {
18140
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18141
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18142
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18143
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18144
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18145
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18146
0
        }
18147
18148
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18149
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18150
0
        {
18151
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18152
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18153
0
        }
18154
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18155
0
        {
18156
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18157
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18158
0
        }
18159
0
        else
18160
0
        {
18161
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18162
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18163
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18164
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18165
0
        }
18166
18167
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18168
0
    }
18169
18170
0
    if (only_write_to_single_node == NULL)
18171
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18172
18173
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18174
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18175
0
    if (child_0_recurse)
18176
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18177
0
    if (child_1_recurse)
18178
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18179
0
}
18180
18181
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18182
0
{
18183
0
    if (node->IsLeafNode())
18184
0
    {
18185
0
        touching_nodes->push_back(node);
18186
0
        return;
18187
0
    }
18188
0
    if (node->ChildNodes[0]->IsVisible)
18189
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18190
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18191
0
    if (node->ChildNodes[1]->IsVisible)
18192
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18193
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18194
0
}
18195
18196
// (Depth-First, Pre-Order)
18197
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18198
0
{
18199
0
    if (node->IsLeafNode())
18200
0
        return;
18201
18202
0
    ImGuiContext& g = *GImGui;
18203
18204
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18205
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18206
0
    if (child_0->IsVisible && child_1->IsVisible)
18207
0
    {
18208
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18209
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18210
0
        IM_ASSERT(axis != ImGuiAxis_None);
18211
0
        ImRect bb;
18212
0
        bb.Min = child_0->Pos;
18213
0
        bb.Max = child_1->Pos;
18214
0
        bb.Min[axis] += child_0->Size[axis];
18215
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18216
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18217
18218
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18219
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18220
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18221
0
        {
18222
0
            ImGuiWindow* window = g.CurrentWindow;
18223
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18224
0
        }
18225
0
        else
18226
0
        {
18227
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18228
            //bb.Max[axis] -= 1;
18229
0
            PushID(node->ID);
18230
18231
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18232
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18233
0
            float min_size = g.Style.WindowMinSize[axis];
18234
0
            float resize_limits[2];
18235
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18236
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18237
18238
0
            ImGuiID splitter_id = GetID("##Splitter");
18239
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18240
0
            {
18241
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18242
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18243
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18244
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18245
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18246
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18247
18248
                // [DEBUG] Render touching nodes & limits
18249
                /*
18250
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18251
                for (int n = 0; n < 2; n++)
18252
                {
18253
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18254
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18255
                    if (axis == ImGuiAxis_X)
18256
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18257
                    else
18258
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18259
                }
18260
                */
18261
0
            }
18262
18263
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18264
0
            float cur_size_0 = child_0->Size[axis];
18265
0
            float cur_size_1 = child_1->Size[axis];
18266
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18267
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18268
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18269
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18270
0
            {
18271
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18272
0
                {
18273
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18274
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18275
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18276
18277
                    // Lock the size of every node that is a sibling of the node we are touching
18278
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18279
0
                    for (int side_n = 0; side_n < 2; side_n++)
18280
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18281
0
                        {
18282
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18283
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18284
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18285
0
                            while (touching_node->ParentNode != node)
18286
0
                            {
18287
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18288
0
                                {
18289
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18290
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18291
0
                                    node_to_preserve->WantLockSizeOnce = true;
18292
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18293
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18294
0
                                }
18295
0
                                touching_node = touching_node->ParentNode;
18296
0
                            }
18297
0
                        }
18298
18299
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18300
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18301
0
                    MarkIniSettingsDirty();
18302
0
                }
18303
0
            }
18304
0
            PopID();
18305
0
        }
18306
0
    }
18307
18308
0
    if (child_0->IsVisible)
18309
0
        DockNodeTreeUpdateSplitter(child_0);
18310
0
    if (child_1->IsVisible)
18311
0
        DockNodeTreeUpdateSplitter(child_1);
18312
0
}
18313
18314
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18315
0
{
18316
0
    if (node->IsLeafNode())
18317
0
        return node;
18318
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18319
0
        return leaf_node;
18320
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18321
0
        return leaf_node;
18322
0
    return NULL;
18323
0
}
18324
18325
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18326
0
{
18327
0
    if (!node->IsVisible)
18328
0
        return NULL;
18329
18330
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18331
0
    ImRect r(node->Pos, node->Pos + node->Size);
18332
0
    r.Expand(dock_spacing * 0.5f);
18333
0
    bool inside = r.Contains(pos);
18334
0
    if (!inside)
18335
0
        return NULL;
18336
18337
0
    if (node->IsLeafNode())
18338
0
        return node;
18339
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18340
0
        return hovered_node;
18341
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18342
0
        return hovered_node;
18343
18344
    // This means we are hovering over the splitter/spacing of a parent node
18345
0
    return node;
18346
0
}
18347
18348
//-----------------------------------------------------------------------------
18349
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18350
//-----------------------------------------------------------------------------
18351
// - SetWindowDock() [Internal]
18352
// - DockSpace()
18353
// - DockSpaceOverViewport()
18354
//-----------------------------------------------------------------------------
18355
18356
// [Internal] Called via SetNextWindowDockID()
18357
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18358
0
{
18359
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18360
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18361
0
        return;
18362
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18363
18364
0
    if (window->DockId == dock_id)
18365
0
        return;
18366
18367
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18368
0
    ImGuiContext& g = *GImGui;
18369
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18370
0
        if (new_node->IsSplitNode())
18371
0
        {
18372
            // Policy: Find central node or latest focused node. We first move back to our root node.
18373
0
            new_node = DockNodeGetRootNode(new_node);
18374
0
            if (new_node->CentralNode)
18375
0
            {
18376
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18377
0
                dock_id = new_node->CentralNode->ID;
18378
0
            }
18379
0
            else
18380
0
            {
18381
0
                dock_id = new_node->LastFocusedNodeId;
18382
0
            }
18383
0
        }
18384
18385
0
    if (window->DockId == dock_id)
18386
0
        return;
18387
18388
0
    if (window->DockNode)
18389
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18390
0
    window->DockId = dock_id;
18391
0
}
18392
18393
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18394
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18395
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18396
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18397
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18398
0
{
18399
0
    ImGuiContext& g = *GImGui;
18400
0
    ImGuiWindow* window = GetCurrentWindowRead();
18401
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18402
0
        return 0;
18403
18404
    // Early out if parent window is hidden/collapsed
18405
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18406
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18407
0
    if (window->SkipItems)
18408
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18409
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18410
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18411
18412
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18413
0
    IM_ASSERT(id != 0);
18414
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18415
0
    if (!node)
18416
0
    {
18417
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18418
0
        node = DockContextAddNode(&g, id);
18419
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18420
0
    }
18421
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18422
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18423
0
    node->SharedFlags = flags;
18424
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18425
18426
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18427
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18428
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18429
0
    {
18430
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18431
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18432
0
        return id;
18433
0
    }
18434
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18435
18436
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18437
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18438
0
    {
18439
0
        node->LastFrameAlive = g.FrameCount;
18440
0
        return id;
18441
0
    }
18442
18443
0
    const ImVec2 content_avail = GetContentRegionAvail();
18444
0
    ImVec2 size = ImTrunc(size_arg);
18445
0
    if (size.x <= 0.0f)
18446
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18447
0
    if (size.y <= 0.0f)
18448
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18449
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18450
18451
0
    node->Pos = window->DC.CursorPos;
18452
0
    node->Size = node->SizeRef = size;
18453
0
    SetNextWindowPos(node->Pos);
18454
0
    SetNextWindowSize(node->Size);
18455
0
    g.NextWindowData.PosUndock = false;
18456
18457
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18458
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18459
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18460
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18461
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18462
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18463
18464
0
    char title[256];
18465
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
18466
18467
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18468
0
    Begin(title, NULL, window_flags);
18469
0
    PopStyleVar();
18470
18471
0
    ImGuiWindow* host_window = g.CurrentWindow;
18472
0
    DockNodeSetupHostWindow(node, host_window);
18473
0
    host_window->ChildId = window->GetID(title);
18474
0
    node->OnlyNodeWithWindows = NULL;
18475
18476
0
    IM_ASSERT(node->IsRootNode());
18477
18478
    // We need to handle the rare case were a central node is missing.
18479
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18480
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18481
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18482
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18483
    // as it doesn't make sense for an empty dockspace to not have this property.
18484
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18485
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18486
18487
    // Update the node
18488
0
    DockNodeUpdate(node);
18489
18490
0
    End();
18491
18492
0
    ImRect bb(node->Pos, node->Pos + size);
18493
0
    ItemSize(size);
18494
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18495
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18496
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18497
18498
0
    return id;
18499
0
}
18500
18501
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18502
// The limitation with this call is that your window won't have a menu bar.
18503
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18504
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18505
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18506
0
{
18507
0
    if (viewport == NULL)
18508
0
        viewport = GetMainViewport();
18509
18510
0
    SetNextWindowPos(viewport->WorkPos);
18511
0
    SetNextWindowSize(viewport->WorkSize);
18512
0
    SetNextWindowViewport(viewport->ID);
18513
18514
0
    ImGuiWindowFlags host_window_flags = 0;
18515
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18516
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18517
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18518
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18519
18520
0
    char label[32];
18521
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
18522
18523
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18524
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18525
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18526
0
    Begin(label, NULL, host_window_flags);
18527
0
    PopStyleVar(3);
18528
18529
0
    ImGuiID dockspace_id = GetID("DockSpace");
18530
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18531
0
    End();
18532
18533
0
    return dockspace_id;
18534
0
}
18535
18536
//-----------------------------------------------------------------------------
18537
// Docking: Builder Functions
18538
//-----------------------------------------------------------------------------
18539
// Very early end-user API to manipulate dock nodes.
18540
// Only available in imgui_internal.h. Expect this API to change/break!
18541
// It is expected that those functions are all called _before_ the dockspace node submission.
18542
//-----------------------------------------------------------------------------
18543
// - DockBuilderDockWindow()
18544
// - DockBuilderGetNode()
18545
// - DockBuilderSetNodePos()
18546
// - DockBuilderSetNodeSize()
18547
// - DockBuilderAddNode()
18548
// - DockBuilderRemoveNode()
18549
// - DockBuilderRemoveNodeChildNodes()
18550
// - DockBuilderRemoveNodeDockedWindows()
18551
// - DockBuilderSplitNode()
18552
// - DockBuilderCopyNodeRec()
18553
// - DockBuilderCopyNode()
18554
// - DockBuilderCopyWindowSettings()
18555
// - DockBuilderCopyDockSpace()
18556
// - DockBuilderFinish()
18557
//-----------------------------------------------------------------------------
18558
18559
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18560
0
{
18561
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18562
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18563
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18564
0
    ImGuiID window_id = ImHashStr(window_name);
18565
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18566
0
    {
18567
        // Apply to created window
18568
0
        ImGuiID prev_node_id = window->DockId;
18569
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18570
0
        if (window->DockId != prev_node_id)
18571
0
            window->DockOrder = -1;
18572
0
    }
18573
0
    else
18574
0
    {
18575
        // Apply to settings
18576
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18577
0
        if (settings == NULL)
18578
0
            settings = CreateNewWindowSettings(window_name);
18579
0
        if (settings->DockId != node_id)
18580
0
            settings->DockOrder = -1;
18581
0
        settings->DockId = node_id;
18582
0
    }
18583
0
}
18584
18585
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18586
0
{
18587
0
    ImGuiContext& g = *GImGui;
18588
0
    return DockContextFindNodeByID(&g, node_id);
18589
0
}
18590
18591
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18592
0
{
18593
0
    ImGuiContext& g = *GImGui;
18594
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18595
0
    if (node == NULL)
18596
0
        return;
18597
0
    node->Pos = pos;
18598
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18599
0
}
18600
18601
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18602
0
{
18603
0
    ImGuiContext& g = *GImGui;
18604
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18605
0
    if (node == NULL)
18606
0
        return;
18607
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18608
0
    node->Size = node->SizeRef = size;
18609
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18610
0
}
18611
18612
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18613
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18614
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18615
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18616
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18617
// - Use (id == 0) to let the system allocate a node identifier.
18618
// - Existing node with a same id will be removed.
18619
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18620
0
{
18621
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18622
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18623
18624
0
    if (node_id != 0)
18625
0
        DockBuilderRemoveNode(node_id);
18626
18627
0
    ImGuiDockNode* node = NULL;
18628
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18629
0
    {
18630
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18631
0
        node = DockContextFindNodeByID(&g, node_id);
18632
0
    }
18633
0
    else
18634
0
    {
18635
0
        node = DockContextAddNode(&g, node_id);
18636
0
        node->SetLocalFlags(flags);
18637
0
    }
18638
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18639
0
    return node->ID;
18640
0
}
18641
18642
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18643
0
{
18644
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18645
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18646
18647
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18648
0
    if (node == NULL)
18649
0
        return;
18650
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18651
0
    DockBuilderRemoveNodeChildNodes(node_id);
18652
    // Node may have moved or deleted if e.g. any merge happened
18653
0
    node = DockContextFindNodeByID(&g, node_id);
18654
0
    if (node == NULL)
18655
0
        return;
18656
0
    if (node->IsCentralNode() && node->ParentNode)
18657
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18658
0
    DockContextRemoveNode(&g, node, true);
18659
0
}
18660
18661
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18662
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18663
0
{
18664
0
    ImGuiContext& g = *GImGui;
18665
0
    ImGuiDockContext* dc = &g.DockContext;
18666
18667
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
18668
0
    if (root_id && root_node == NULL)
18669
0
        return;
18670
0
    bool has_central_node = false;
18671
18672
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18673
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18674
18675
    // Process active windows
18676
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18677
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18678
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18679
0
        {
18680
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18681
0
            if (want_removal)
18682
0
            {
18683
0
                if (node->IsCentralNode())
18684
0
                    has_central_node = true;
18685
0
                if (root_id != 0)
18686
0
                    DockContextQueueNotifyRemovedNode(&g, node);
18687
0
                if (root_node)
18688
0
                {
18689
0
                    DockNodeMoveWindows(root_node, node);
18690
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18691
0
                }
18692
0
                nodes_to_remove.push_back(node);
18693
0
            }
18694
0
        }
18695
18696
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18697
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18698
0
    if (root_node)
18699
0
    {
18700
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18701
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18702
0
    }
18703
18704
    // Apply to settings
18705
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18706
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18707
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18708
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18709
0
                {
18710
0
                    settings->DockId = root_id;
18711
0
                    break;
18712
0
                }
18713
18714
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18715
0
    if (nodes_to_remove.Size > 1)
18716
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18717
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18718
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
18719
18720
0
    if (root_id == 0)
18721
0
    {
18722
0
        dc->Nodes.Clear();
18723
0
        dc->Requests.clear();
18724
0
    }
18725
0
    else if (has_central_node)
18726
0
    {
18727
0
        root_node->CentralNode = root_node;
18728
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18729
0
    }
18730
0
}
18731
18732
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18733
0
{
18734
    // Clear references in settings
18735
0
    ImGuiContext& g = *GImGui;
18736
0
    if (clear_settings_refs)
18737
0
    {
18738
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18739
0
        {
18740
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18741
0
            if (!want_removal && settings->DockId != 0)
18742
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
18743
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18744
0
                        want_removal = true;
18745
0
            if (want_removal)
18746
0
                settings->DockId = 0;
18747
0
        }
18748
0
    }
18749
18750
    // Clear references in windows
18751
0
    for (int n = 0; n < g.Windows.Size; n++)
18752
0
    {
18753
0
        ImGuiWindow* window = g.Windows[n];
18754
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18755
0
        if (want_removal)
18756
0
        {
18757
0
            const ImGuiID backup_dock_id = window->DockId;
18758
0
            IM_UNUSED(backup_dock_id);
18759
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
18760
0
            if (!clear_settings_refs)
18761
0
                IM_ASSERT(window->DockId == backup_dock_id);
18762
0
        }
18763
0
    }
18764
0
}
18765
18766
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18767
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18768
// FIXME-DOCK: We are not exposing nor using split_outer.
18769
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18770
0
{
18771
0
    ImGuiContext& g = *GImGui;
18772
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18773
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18774
18775
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18776
0
    if (node == NULL)
18777
0
    {
18778
0
        IM_ASSERT(node != NULL);
18779
0
        return 0;
18780
0
    }
18781
18782
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18783
18784
0
    ImGuiDockRequest req;
18785
0
    req.Type = ImGuiDockRequestType_Split;
18786
0
    req.DockTargetWindow = NULL;
18787
0
    req.DockTargetNode = node;
18788
0
    req.DockPayload = NULL;
18789
0
    req.DockSplitDir = split_dir;
18790
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18791
0
    req.DockSplitOuter = false;
18792
0
    DockContextProcessDock(&g, &req);
18793
18794
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18795
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18796
0
    if (out_id_at_dir)
18797
0
        *out_id_at_dir = id_at_dir;
18798
0
    if (out_id_at_opposite_dir)
18799
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18800
0
    return id_at_dir;
18801
0
}
18802
18803
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18804
0
{
18805
0
    ImGuiContext& g = *GImGui;
18806
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18807
0
    dst_node->SharedFlags = src_node->SharedFlags;
18808
0
    dst_node->LocalFlags = src_node->LocalFlags;
18809
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18810
0
    dst_node->Pos = src_node->Pos;
18811
0
    dst_node->Size = src_node->Size;
18812
0
    dst_node->SizeRef = src_node->SizeRef;
18813
0
    dst_node->SplitAxis = src_node->SplitAxis;
18814
0
    dst_node->UpdateMergedFlags();
18815
18816
0
    out_node_remap_pairs->push_back(src_node->ID);
18817
0
    out_node_remap_pairs->push_back(dst_node->ID);
18818
18819
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18820
0
        if (src_node->ChildNodes[child_n])
18821
0
        {
18822
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18823
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18824
0
        }
18825
18826
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18827
0
    return dst_node;
18828
0
}
18829
18830
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18831
0
{
18832
0
    ImGuiContext& g = *GImGui;
18833
0
    IM_ASSERT(src_node_id != 0);
18834
0
    IM_ASSERT(dst_node_id != 0);
18835
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18836
18837
0
    DockBuilderRemoveNode(dst_node_id);
18838
18839
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
18840
0
    IM_ASSERT(src_node != NULL);
18841
18842
0
    out_node_remap_pairs->clear();
18843
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18844
18845
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18846
0
}
18847
18848
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18849
0
{
18850
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18851
0
    if (src_window == NULL)
18852
0
        return;
18853
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18854
0
    {
18855
0
        dst_window->Pos = src_window->Pos;
18856
0
        dst_window->Size = src_window->Size;
18857
0
        dst_window->SizeFull = src_window->SizeFull;
18858
0
        dst_window->Collapsed = src_window->Collapsed;
18859
0
    }
18860
0
    else
18861
0
    {
18862
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18863
0
        if (!dst_settings)
18864
0
            dst_settings = CreateNewWindowSettings(dst_name);
18865
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18866
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18867
0
        {
18868
0
            dst_settings->ViewportPos = window_pos_2ih;
18869
0
            dst_settings->ViewportId = src_window->ViewportId;
18870
0
            dst_settings->Pos = ImVec2ih(0, 0);
18871
0
        }
18872
0
        else
18873
0
        {
18874
0
            dst_settings->Pos = window_pos_2ih;
18875
0
        }
18876
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18877
0
        dst_settings->Collapsed = src_window->Collapsed;
18878
0
    }
18879
0
}
18880
18881
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18882
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18883
0
{
18884
0
    ImGuiContext& g = *GImGui;
18885
0
    IM_ASSERT(src_dockspace_id != 0);
18886
0
    IM_ASSERT(dst_dockspace_id != 0);
18887
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18888
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18889
18890
    // Duplicate entire dock
18891
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18892
    // whereas we could attempt to at least keep them together in a new, same floating node.
18893
0
    ImVector<ImGuiID> node_remap_pairs;
18894
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18895
18896
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18897
    // (The windows associated to src_dockspace_id are staying in place)
18898
0
    ImVector<ImGuiID> src_windows;
18899
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18900
0
    {
18901
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18902
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18903
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18904
0
        src_windows.push_back(src_window_id);
18905
18906
        // Search in the remapping tables
18907
0
        ImGuiID src_dock_id = 0;
18908
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18909
0
            src_dock_id = src_window->DockId;
18910
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18911
0
            src_dock_id = src_window_settings->DockId;
18912
0
        ImGuiID dst_dock_id = 0;
18913
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18914
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18915
0
            {
18916
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18917
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18918
0
                break;
18919
0
            }
18920
18921
0
        if (dst_dock_id != 0)
18922
0
        {
18923
            // Docked windows gets redocked into the new node hierarchy.
18924
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18925
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18926
0
        }
18927
0
        else
18928
0
        {
18929
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18930
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18931
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18932
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18933
0
        }
18934
0
    }
18935
18936
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18937
    // Find those windows and move to them to the cloned dock node. This may be optional?
18938
    // Dock those are a second step as undocking would invalidate source dock nodes.
18939
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18940
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18941
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18942
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18943
0
        {
18944
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18945
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18946
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18947
0
            {
18948
0
                ImGuiWindow* window = node->Windows[window_n];
18949
0
                if (src_windows.contains(window->ID))
18950
0
                    continue;
18951
18952
                // Docked windows gets redocked into the new node hierarchy.
18953
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18954
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18955
0
            }
18956
0
        }
18957
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18958
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18959
0
}
18960
18961
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18962
void ImGui::DockBuilderFinish(ImGuiID root_id)
18963
0
{
18964
0
    ImGuiContext& g = *GImGui;
18965
    //DockContextRebuild(&g);
18966
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
18967
0
}
18968
18969
//-----------------------------------------------------------------------------
18970
// Docking: Begin/End Support Functions (called from Begin/End)
18971
//-----------------------------------------------------------------------------
18972
// - GetWindowAlwaysWantOwnTabBar()
18973
// - DockContextBindNodeToWindow()
18974
// - BeginDocked()
18975
// - BeginDockableDragDropSource()
18976
// - BeginDockableDragDropTarget()
18977
//-----------------------------------------------------------------------------
18978
18979
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18980
0
{
18981
0
    ImGuiContext& g = *GImGui;
18982
0
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18983
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18984
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18985
0
                return true;
18986
0
    return false;
18987
0
}
18988
18989
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18990
0
{
18991
0
    ImGuiContext& g = *ctx;
18992
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18993
0
    IM_ASSERT(window->DockNode == NULL);
18994
18995
    // We should not be docking into a split node (SetWindowDock should avoid this)
18996
0
    if (node && node->IsSplitNode())
18997
0
    {
18998
0
        DockContextProcessUndockWindow(ctx, window);
18999
0
        return NULL;
19000
0
    }
19001
19002
    // Create node
19003
0
    if (node == NULL)
19004
0
    {
19005
0
        node = DockContextAddNode(ctx, window->DockId);
19006
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
19007
0
        node->LastFrameAlive = g.FrameCount;
19008
0
    }
19009
19010
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
19011
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
19012
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
19013
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
19014
0
    if (!node->IsVisible)
19015
0
    {
19016
0
        ImGuiDockNode* ancestor_node = node;
19017
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
19018
0
            ancestor_node = ancestor_node->ParentNode;
19019
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
19020
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
19021
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
19022
0
    }
19023
19024
    // Add window to node
19025
0
    bool node_was_visible = node->IsVisible;
19026
0
    DockNodeAddWindow(node, window, true);
19027
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19028
0
    IM_ASSERT(node == window->DockNode);
19029
0
    return node;
19030
0
}
19031
19032
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19033
0
{
19034
0
    ImGuiContext& g = *GImGui;
19035
19036
    // Clear fields ahead so most early-out paths don't have to do it
19037
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19038
19039
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19040
0
    if (auto_dock_node)
19041
0
    {
19042
0
        if (window->DockId == 0)
19043
0
        {
19044
0
            IM_ASSERT(window->DockNode == NULL);
19045
0
            window->DockId = DockContextGenNodeID(&g);
19046
0
        }
19047
0
    }
19048
0
    else
19049
0
    {
19050
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19051
0
        bool want_undock = false;
19052
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19053
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19054
0
        if (want_undock)
19055
0
        {
19056
0
            DockContextProcessUndockWindow(&g, window);
19057
0
            return;
19058
0
        }
19059
0
    }
19060
19061
    // Bind to our dock node
19062
0
    ImGuiDockNode* node = window->DockNode;
19063
0
    if (node != NULL)
19064
0
        IM_ASSERT(window->DockId == node->ID);
19065
0
    if (window->DockId != 0 && node == NULL)
19066
0
    {
19067
0
        node = DockContextBindNodeToWindow(&g, window);
19068
0
        if (node == NULL)
19069
0
            return;
19070
0
    }
19071
19072
#if 0
19073
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19074
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19075
    {
19076
        DockContextProcessUndockWindow(ctx, window);
19077
        return;
19078
    }
19079
#endif
19080
19081
    // Undock if our dockspace node disappeared
19082
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19083
0
    if (node->LastFrameAlive < g.FrameCount)
19084
0
    {
19085
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19086
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19087
0
        if (root_node->LastFrameAlive < g.FrameCount)
19088
0
            DockContextProcessUndockWindow(&g, window);
19089
0
        else
19090
0
            window->DockIsActive = true;
19091
0
        return;
19092
0
    }
19093
19094
    // Store style overrides
19095
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19096
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19097
19098
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19099
    // and never create neither a host window neither a tab bar.
19100
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19101
0
    if (node->HostWindow == NULL)
19102
0
    {
19103
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19104
0
            window->DockIsActive = true;
19105
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19106
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19107
0
        return;
19108
0
    }
19109
19110
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19111
0
    IM_ASSERT(node->HostWindow);
19112
0
    IM_ASSERT(node->IsLeafNode());
19113
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19114
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19115
19116
    // Undock if we are submitted earlier than the host window
19117
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19118
0
    {
19119
0
        DockContextProcessUndockWindow(&g, window);
19120
0
        return;
19121
0
    }
19122
19123
    // Position/Size window
19124
0
    SetNextWindowPos(node->Pos);
19125
0
    SetNextWindowSize(node->Size);
19126
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19127
0
    window->DockIsActive = true;
19128
0
    window->DockNodeIsVisible = true;
19129
0
    window->DockTabIsVisible = false;
19130
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19131
0
        return;
19132
19133
    // When the window is selected we mark it as visible.
19134
0
    if (node->VisibleWindow == window)
19135
0
        window->DockTabIsVisible = true;
19136
19137
    // Update window flag
19138
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19139
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19140
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19141
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19142
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19143
0
    else
19144
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19145
19146
    // Save new dock order only if the window has been visible once already
19147
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19148
0
    if (node->TabBar && window->WasActive)
19149
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19150
19151
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19152
0
        *p_open = false;
19153
19154
    // Update ChildId to allow returning from Child to Parent with Escape
19155
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19156
0
    window->ChildId = parent_window->GetID(window->Name);
19157
0
}
19158
19159
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19160
0
{
19161
0
    ImGuiContext& g = *GImGui;
19162
0
    IM_ASSERT(g.ActiveId == window->MoveId);
19163
0
    IM_ASSERT(g.MovingWindow == window);
19164
0
    IM_ASSERT(g.CurrentWindow == window);
19165
19166
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19167
0
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19168
0
    {
19169
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19170
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19171
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19172
0
        IM_ASSERT(g.NextWindowData.Flags == 0);
19173
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19174
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19175
0
        return;
19176
0
    }
19177
19178
0
    g.LastItemData.ID = window->MoveId;
19179
0
    window = window->RootWindowDockTree;
19180
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19181
0
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19182
0
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
19183
0
    {
19184
0
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19185
0
        EndDragDropSource();
19186
19187
        // Store style overrides
19188
0
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19189
0
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19190
0
    }
19191
0
}
19192
19193
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19194
0
{
19195
0
    ImGuiContext& g = *GImGui;
19196
19197
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19198
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19199
0
    if (!g.DragDropActive)
19200
0
        return;
19201
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19202
0
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19203
0
        return;
19204
19205
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19206
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19207
0
    const ImGuiPayload* payload = &g.DragDropPayload;
19208
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19209
0
    {
19210
0
        EndDragDropTarget();
19211
0
        return;
19212
0
    }
19213
19214
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19215
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19216
0
    {
19217
        // Select target node
19218
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19219
0
        bool dock_into_floating_window = false;
19220
0
        ImGuiDockNode* node = NULL;
19221
0
        if (window->DockNodeAsHost)
19222
0
        {
19223
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19224
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19225
19226
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19227
            // In this case we need to fallback into any leaf mode, possibly the central node.
19228
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19229
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19230
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19231
0
        }
19232
0
        else
19233
0
        {
19234
0
            if (window->DockNode)
19235
0
                node = window->DockNode;
19236
0
            else
19237
0
                dock_into_floating_window = true; // Dock into a regular window
19238
0
        }
19239
19240
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19241
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19242
19243
        // Preview docking request and find out split direction/ratio
19244
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19245
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19246
0
        if (do_preview && (node != NULL || dock_into_floating_window))
19247
0
        {
19248
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19249
0
            ImGuiDockPreviewData split_inner;
19250
0
            ImGuiDockPreviewData split_outer;
19251
0
            ImGuiDockPreviewData* split_data = &split_inner;
19252
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19253
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19254
0
                {
19255
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19256
0
                    if (split_outer.IsSplitDirExplicit)
19257
0
                        split_data = &split_outer;
19258
0
                }
19259
0
            if (!node || node->IsLeafNode())
19260
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19261
0
            if (split_data == &split_outer)
19262
0
                split_inner.IsDropAllowed = false;
19263
19264
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19265
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19266
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19267
19268
            // Queue docking request
19269
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19270
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19271
0
        }
19272
0
    }
19273
0
    EndDragDropTarget();
19274
0
}
19275
19276
//-----------------------------------------------------------------------------
19277
// Docking: Settings
19278
//-----------------------------------------------------------------------------
19279
// - DockSettingsRenameNodeReferences()
19280
// - DockSettingsRemoveNodeReferences()
19281
// - DockSettingsFindNodeSettings()
19282
// - DockSettingsHandler_ApplyAll()
19283
// - DockSettingsHandler_ReadOpen()
19284
// - DockSettingsHandler_ReadLine()
19285
// - DockSettingsHandler_DockNodeToSettings()
19286
// - DockSettingsHandler_WriteAll()
19287
//-----------------------------------------------------------------------------
19288
19289
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19290
0
{
19291
0
    ImGuiContext& g = *GImGui;
19292
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19293
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19294
0
    {
19295
0
        ImGuiWindow* window = g.Windows[window_n];
19296
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19297
0
            window->DockId = new_node_id;
19298
0
    }
19299
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19300
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19301
0
        if (settings->DockId == old_node_id)
19302
0
            settings->DockId = new_node_id;
19303
0
}
19304
19305
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19306
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19307
0
{
19308
0
    ImGuiContext& g = *GImGui;
19309
0
    int found = 0;
19310
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19311
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19312
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19313
0
            if (settings->DockId == node_ids[node_n])
19314
0
            {
19315
0
                settings->DockId = 0;
19316
0
                settings->DockOrder = -1;
19317
0
                if (++found < node_ids_count)
19318
0
                    break;
19319
0
                return;
19320
0
            }
19321
0
}
19322
19323
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19324
0
{
19325
    // FIXME-OPT
19326
0
    ImGuiDockContext* dc = &ctx->DockContext;
19327
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19328
0
        if (dc->NodesSettings[n].ID == id)
19329
0
            return &dc->NodesSettings[n];
19330
0
    return NULL;
19331
0
}
19332
19333
// Clear settings data
19334
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19335
0
{
19336
0
    ImGuiDockContext* dc = &ctx->DockContext;
19337
0
    dc->NodesSettings.clear();
19338
0
    DockContextClearNodes(ctx, 0, true);
19339
0
}
19340
19341
// Recreate nodes based on settings data
19342
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19343
0
{
19344
    // Prune settings at boot time only
19345
0
    ImGuiDockContext* dc = &ctx->DockContext;
19346
0
    if (ctx->Windows.Size == 0)
19347
0
        DockContextPruneUnusedSettingsNodes(ctx);
19348
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19349
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19350
0
}
19351
19352
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19353
0
{
19354
0
    if (strcmp(name, "Data") != 0)
19355
0
        return NULL;
19356
0
    return (void*)1;
19357
0
}
19358
19359
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19360
0
{
19361
0
    char c = 0;
19362
0
    int x = 0, y = 0;
19363
0
    int r = 0;
19364
19365
    // Parsing, e.g.
19366
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19367
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19368
    // Important: this code expect currently fields in a fixed order.
19369
0
    ImGuiDockNodeSettings node;
19370
0
    line = ImStrSkipBlank(line);
19371
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19372
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19373
0
    else return;
19374
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19375
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19376
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19377
0
    if (node.ParentNodeId == 0)
19378
0
    {
19379
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19380
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19381
0
    }
19382
0
    else
19383
0
    {
19384
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19385
0
    }
19386
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19387
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19388
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19389
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19390
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19391
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19392
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19393
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19394
0
    if (node.ParentNodeId != 0)
19395
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19396
0
            node.Depth = parent_settings->Depth + 1;
19397
0
    ctx->DockContext.NodesSettings.push_back(node);
19398
0
}
19399
19400
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19401
0
{
19402
0
    ImGuiDockNodeSettings node_settings;
19403
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19404
0
    node_settings.ID = node->ID;
19405
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19406
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19407
0
    node_settings.SelectedTabId = node->SelectedTabId;
19408
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19409
0
    node_settings.Depth = (char)depth;
19410
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19411
0
    node_settings.Pos = ImVec2ih(node->Pos);
19412
0
    node_settings.Size = ImVec2ih(node->Size);
19413
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19414
0
    dc->NodesSettings.push_back(node_settings);
19415
0
    if (node->ChildNodes[0])
19416
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19417
0
    if (node->ChildNodes[1])
19418
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19419
0
}
19420
19421
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19422
0
{
19423
0
    ImGuiContext& g = *ctx;
19424
0
    ImGuiDockContext* dc = &ctx->DockContext;
19425
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19426
0
        return;
19427
19428
    // Gather settings data
19429
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19430
0
    dc->NodesSettings.resize(0);
19431
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19432
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19433
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19434
0
            if (node->IsRootNode())
19435
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19436
19437
0
    int max_depth = 0;
19438
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19439
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19440
19441
    // Write to text buffer
19442
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19443
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19444
0
    {
19445
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19446
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19447
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19448
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19449
0
        if (node_settings->ParentNodeId)
19450
0
        {
19451
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19452
0
        }
19453
0
        else
19454
0
        {
19455
0
            if (node_settings->ParentWindowId)
19456
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19457
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19458
0
        }
19459
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19460
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19461
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19462
0
            buf->appendf(" NoResize=1");
19463
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19464
0
            buf->appendf(" CentralNode=1");
19465
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19466
0
            buf->appendf(" NoTabBar=1");
19467
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19468
0
            buf->appendf(" HiddenTabBar=1");
19469
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19470
0
            buf->appendf(" NoWindowMenuButton=1");
19471
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19472
0
            buf->appendf(" NoCloseButton=1");
19473
0
        if (node_settings->SelectedTabId)
19474
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19475
19476
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19477
0
        if (g.IO.ConfigDebugIniSettings)
19478
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19479
0
            {
19480
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19481
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19482
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19483
                // Iterate settings so we can give info about windows that didn't exist during the session.
19484
0
                int contains_window = 0;
19485
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19486
0
                    if (settings->DockId == node_settings->ID)
19487
0
                    {
19488
0
                        if (contains_window++ == 0)
19489
0
                            buf->appendf(" ; contains ");
19490
0
                        buf->appendf("'%s' ", settings->GetName());
19491
0
                    }
19492
0
            }
19493
19494
0
        buf->appendf("\n");
19495
0
    }
19496
0
    buf->appendf("\n");
19497
0
}
19498
19499
19500
//-----------------------------------------------------------------------------
19501
// [SECTION] PLATFORM DEPENDENT HELPERS
19502
//-----------------------------------------------------------------------------
19503
19504
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19505
19506
#ifdef _MSC_VER
19507
#pragma comment(lib, "user32")
19508
#pragma comment(lib, "kernel32")
19509
#endif
19510
19511
// Win32 clipboard implementation
19512
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19513
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19514
{
19515
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19516
    g.ClipboardHandlerData.clear();
19517
    if (!::OpenClipboard(NULL))
19518
        return NULL;
19519
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19520
    if (wbuf_handle == NULL)
19521
    {
19522
        ::CloseClipboard();
19523
        return NULL;
19524
    }
19525
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19526
    {
19527
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19528
        g.ClipboardHandlerData.resize(buf_len);
19529
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19530
    }
19531
    ::GlobalUnlock(wbuf_handle);
19532
    ::CloseClipboard();
19533
    return g.ClipboardHandlerData.Data;
19534
}
19535
19536
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19537
{
19538
    if (!::OpenClipboard(NULL))
19539
        return;
19540
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19541
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19542
    if (wbuf_handle == NULL)
19543
    {
19544
        ::CloseClipboard();
19545
        return;
19546
    }
19547
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19548
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19549
    ::GlobalUnlock(wbuf_handle);
19550
    ::EmptyClipboard();
19551
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19552
        ::GlobalFree(wbuf_handle);
19553
    ::CloseClipboard();
19554
}
19555
19556
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19557
19558
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19559
static PasteboardRef main_clipboard = 0;
19560
19561
// OSX clipboard implementation
19562
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19563
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19564
{
19565
    if (!main_clipboard)
19566
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19567
    PasteboardClear(main_clipboard);
19568
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19569
    if (cf_data)
19570
    {
19571
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19572
        CFRelease(cf_data);
19573
    }
19574
}
19575
19576
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19577
{
19578
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19579
    if (!main_clipboard)
19580
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19581
    PasteboardSynchronize(main_clipboard);
19582
19583
    ItemCount item_count = 0;
19584
    PasteboardGetItemCount(main_clipboard, &item_count);
19585
    for (ItemCount i = 0; i < item_count; i++)
19586
    {
19587
        PasteboardItemID item_id = 0;
19588
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19589
        CFArrayRef flavor_type_array = 0;
19590
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19591
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19592
        {
19593
            CFDataRef cf_data;
19594
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19595
            {
19596
                g.ClipboardHandlerData.clear();
19597
                int length = (int)CFDataGetLength(cf_data);
19598
                g.ClipboardHandlerData.resize(length + 1);
19599
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19600
                g.ClipboardHandlerData[length] = 0;
19601
                CFRelease(cf_data);
19602
                return g.ClipboardHandlerData.Data;
19603
            }
19604
        }
19605
    }
19606
    return NULL;
19607
}
19608
19609
#else
19610
19611
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19612
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19613
0
{
19614
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19615
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19616
0
}
19617
19618
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19619
0
{
19620
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19621
0
    g.ClipboardHandlerData.clear();
19622
0
    const char* text_end = text + strlen(text);
19623
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19624
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19625
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19626
0
}
19627
19628
#endif
19629
19630
// Win32 API IME support (for Asian languages, etc.)
19631
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19632
19633
#include <imm.h>
19634
#ifdef _MSC_VER
19635
#pragma comment(lib, "imm32")
19636
#endif
19637
19638
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19639
{
19640
    // Notify OS Input Method Editor of text input position
19641
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19642
    if (hwnd == 0)
19643
        return;
19644
19645
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19646
    if (HIMC himc = ::ImmGetContext(hwnd))
19647
    {
19648
        COMPOSITIONFORM composition_form = {};
19649
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19650
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19651
        composition_form.dwStyle = CFS_FORCE_POSITION;
19652
        ::ImmSetCompositionWindow(himc, &composition_form);
19653
        CANDIDATEFORM candidate_form = {};
19654
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19655
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19656
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19657
        ::ImmSetCandidateWindow(himc, &candidate_form);
19658
        ::ImmReleaseContext(hwnd, himc);
19659
    }
19660
}
19661
19662
#else
19663
19664
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19665
19666
#endif
19667
19668
//-----------------------------------------------------------------------------
19669
// [SECTION] METRICS/DEBUGGER WINDOW
19670
//-----------------------------------------------------------------------------
19671
// - DebugRenderViewportThumbnail() [Internal]
19672
// - RenderViewportsThumbnails() [Internal]
19673
// - DebugTextEncoding()
19674
// - MetricsHelpMarker() [Internal]
19675
// - ShowFontAtlas() [Internal]
19676
// - ShowMetricsWindow()
19677
// - DebugNodeColumns() [Internal]
19678
// - DebugNodeDockNode() [Internal]
19679
// - DebugNodeDrawList() [Internal]
19680
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19681
// - DebugNodeFont() [Internal]
19682
// - DebugNodeFontGlyph() [Internal]
19683
// - DebugNodeStorage() [Internal]
19684
// - DebugNodeTabBar() [Internal]
19685
// - DebugNodeViewport() [Internal]
19686
// - DebugNodeWindow() [Internal]
19687
// - DebugNodeWindowSettings() [Internal]
19688
// - DebugNodeWindowsList() [Internal]
19689
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19690
//-----------------------------------------------------------------------------
19691
19692
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19693
19694
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19695
0
{
19696
0
    ImGuiContext& g = *GImGui;
19697
0
    ImGuiWindow* window = g.CurrentWindow;
19698
19699
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19700
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19701
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19702
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19703
0
    for (ImGuiWindow* thumb_window : g.Windows)
19704
0
    {
19705
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19706
0
            continue;
19707
0
        if (thumb_window->Viewport != viewport)
19708
0
            continue;
19709
19710
0
        ImRect thumb_r = thumb_window->Rect();
19711
0
        ImRect title_r = thumb_window->TitleBarRect();
19712
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
19713
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
19714
0
        thumb_r.ClipWithFull(bb);
19715
0
        title_r.ClipWithFull(bb);
19716
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19717
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19718
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19719
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19720
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19721
0
    }
19722
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19723
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
19724
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
19725
0
}
19726
19727
static void RenderViewportsThumbnails()
19728
0
{
19729
0
    ImGuiContext& g = *GImGui;
19730
0
    ImGuiWindow* window = g.CurrentWindow;
19731
19732
    // Draw monitor and calculate their boundaries
19733
0
    float SCALE = 1.0f / 8.0f;
19734
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19735
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19736
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
19737
0
    ImVec2 p = window->DC.CursorPos;
19738
0
    ImVec2 off = p - bb_full.Min * SCALE;
19739
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
19740
0
    {
19741
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
19742
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
19743
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
19744
0
    }
19745
19746
    // Draw viewports
19747
0
    for (ImGuiViewportP* viewport : g.Viewports)
19748
0
    {
19749
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19750
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19751
0
    }
19752
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19753
0
}
19754
19755
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19756
0
{
19757
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19758
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19759
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19760
0
}
19761
19762
// Draw an arbitrary US keyboard layout to visualize translated keys
19763
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19764
0
{
19765
0
    const float scale = ImGui::GetFontSize() / 13.0f;
19766
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
19767
0
    const float  key_rounding = 3.0f * scale;
19768
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
19769
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
19770
0
    const float  key_face_rounding = 2.0f * scale;
19771
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
19772
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19773
0
    const float  key_row_offset = 9.0f * scale;
19774
19775
0
    ImVec2 board_min = GetCursorScreenPos();
19776
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19777
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19778
19779
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19780
0
    const KeyLayoutData keys_to_display[] =
19781
0
    {
19782
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19783
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19784
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19785
0
    };
19786
19787
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19788
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19789
0
    Dummy(board_max - board_min);
19790
0
    if (!IsItemVisible())
19791
0
        return;
19792
0
    draw_list->PushClipRect(board_min, board_max, true);
19793
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19794
0
    {
19795
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19796
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19797
0
        ImVec2 key_max = key_min + key_size;
19798
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19799
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19800
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19801
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19802
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19803
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19804
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19805
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19806
0
        if (IsKeyDown(key_data->Key))
19807
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19808
0
    }
19809
0
    draw_list->PopClipRect();
19810
0
}
19811
19812
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19813
void ImGui::DebugTextEncoding(const char* str)
19814
0
{
19815
0
    Text("Text: \"%s\"", str);
19816
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19817
0
        return;
19818
0
    TableSetupColumn("Offset");
19819
0
    TableSetupColumn("UTF-8");
19820
0
    TableSetupColumn("Glyph");
19821
0
    TableSetupColumn("Codepoint");
19822
0
    TableHeadersRow();
19823
0
    for (const char* p = str; *p != 0; )
19824
0
    {
19825
0
        unsigned int c;
19826
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19827
0
        TableNextColumn();
19828
0
        Text("%d", (int)(p - str));
19829
0
        TableNextColumn();
19830
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19831
0
        {
19832
0
            if (byte_index > 0)
19833
0
                SameLine();
19834
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19835
0
        }
19836
0
        TableNextColumn();
19837
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19838
0
            TextUnformatted(p, p + c_utf8_len);
19839
0
        else
19840
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19841
0
        TableNextColumn();
19842
0
        Text("U+%04X", (int)c);
19843
0
        p += c_utf8_len;
19844
0
    }
19845
0
    EndTable();
19846
0
}
19847
19848
static void DebugFlashStyleColorStop()
19849
0
{
19850
0
    ImGuiContext& g = *GImGui;
19851
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
19852
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
19853
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
19854
0
}
19855
19856
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
19857
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
19858
0
{
19859
0
    ImGuiContext& g = *GImGui;
19860
0
    DebugFlashStyleColorStop();
19861
0
    g.DebugFlashStyleColorTime = 0.5f;
19862
0
    g.DebugFlashStyleColorIdx = idx;
19863
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
19864
0
}
19865
19866
void ImGui::UpdateDebugToolFlashStyleColor()
19867
0
{
19868
0
    ImGuiContext& g = *GImGui;
19869
0
    if (g.DebugFlashStyleColorTime <= 0.0f)
19870
0
        return;
19871
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
19872
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
19873
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
19874
0
        DebugFlashStyleColorStop();
19875
0
}
19876
19877
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19878
static void MetricsHelpMarker(const char* desc)
19879
0
{
19880
0
    ImGui::TextDisabled("(?)");
19881
0
    if (ImGui::BeginItemTooltip())
19882
0
    {
19883
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19884
0
        ImGui::TextUnformatted(desc);
19885
0
        ImGui::PopTextWrapPos();
19886
0
        ImGui::EndTooltip();
19887
0
    }
19888
0
}
19889
19890
// [DEBUG] List fonts in a font atlas and display its texture
19891
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19892
0
{
19893
0
    for (ImFont* font : atlas->Fonts)
19894
0
    {
19895
0
        PushID(font);
19896
0
        DebugNodeFont(font);
19897
0
        PopID();
19898
0
    }
19899
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19900
0
    {
19901
0
        ImGuiContext& g = *GImGui;
19902
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19903
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19904
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19905
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19906
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19907
0
        TreePop();
19908
0
    }
19909
0
}
19910
19911
void ImGui::ShowMetricsWindow(bool* p_open)
19912
0
{
19913
0
    ImGuiContext& g = *GImGui;
19914
0
    ImGuiIO& io = g.IO;
19915
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19916
0
    if (cfg->ShowDebugLog)
19917
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19918
0
    if (cfg->ShowIDStackTool)
19919
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19920
19921
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19922
0
    {
19923
0
        End();
19924
0
        return;
19925
0
    }
19926
19927
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
19928
0
    DebugBreakClearData();
19929
19930
    // Basic info
19931
0
    Text("Dear ImGui %s", GetVersion());
19932
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19933
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19934
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19935
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19936
19937
0
    Separator();
19938
19939
    // Debugging enums
19940
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19941
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19942
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19943
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19944
0
    if (cfg->ShowWindowsRectsType < 0)
19945
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19946
0
    if (cfg->ShowTablesRectsType < 0)
19947
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19948
19949
0
    struct Funcs
19950
0
    {
19951
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19952
0
        {
19953
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19954
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19955
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19956
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19957
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19958
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19959
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19960
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19961
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19962
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19963
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
19964
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
19965
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19966
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19967
0
            IM_ASSERT(0);
19968
0
            return ImRect();
19969
0
        }
19970
19971
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19972
0
        {
19973
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19974
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19975
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19976
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19977
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19978
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19979
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19980
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19981
0
            IM_ASSERT(0);
19982
0
            return ImRect();
19983
0
        }
19984
0
    };
19985
19986
    // Tools
19987
0
    if (TreeNode("Tools"))
19988
0
    {
19989
        // Debug Break features
19990
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19991
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
19992
0
        SameLine();
19993
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19994
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19995
0
            DebugStartItemPicker();
19996
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
19997
19998
0
        SeparatorText("Visualize");
19999
20000
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
20001
0
        SameLine();
20002
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
20003
20004
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
20005
0
        SameLine();
20006
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
20007
20008
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
20009
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
20010
0
        SameLine();
20011
0
        SetNextItemWidth(GetFontSize() * 12);
20012
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
20013
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
20014
0
        {
20015
0
            BulletText("'%s':", g.NavWindow->Name);
20016
0
            Indent();
20017
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
20018
0
            {
20019
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
20020
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
20021
0
            }
20022
0
            Unindent();
20023
0
        }
20024
20025
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
20026
0
        SameLine();
20027
0
        SetNextItemWidth(GetFontSize() * 12);
20028
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20029
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20030
0
        {
20031
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20032
0
            {
20033
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20034
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20035
0
                    continue;
20036
20037
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20038
0
                if (IsItemHovered())
20039
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20040
0
                Indent();
20041
0
                char buf[128];
20042
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20043
0
                {
20044
0
                    if (rect_n >= TRT_ColumnsRect)
20045
0
                    {
20046
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20047
0
                            continue;
20048
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20049
0
                        {
20050
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20051
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20052
0
                            Selectable(buf);
20053
0
                            if (IsItemHovered())
20054
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20055
0
                        }
20056
0
                    }
20057
0
                    else
20058
0
                    {
20059
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20060
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20061
0
                        Selectable(buf);
20062
0
                        if (IsItemHovered())
20063
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20064
0
                    }
20065
0
                }
20066
0
                Unindent();
20067
0
            }
20068
0
        }
20069
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20070
20071
0
        SeparatorText("Validate");
20072
20073
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20074
0
        SameLine();
20075
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20076
20077
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20078
0
        SameLine();
20079
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20080
0
        if (cfg->ShowTextEncodingViewer)
20081
0
        {
20082
0
            static char buf[64] = "";
20083
0
            SetNextItemWidth(-FLT_MIN);
20084
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20085
0
            if (buf[0] != 0)
20086
0
                DebugTextEncoding(buf);
20087
0
        }
20088
20089
0
        TreePop();
20090
0
    }
20091
20092
    // Windows
20093
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20094
0
    {
20095
        //SetNextItemOpen(true, ImGuiCond_Once);
20096
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20097
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20098
0
        if (TreeNode("By submission order (begin stack)"))
20099
0
        {
20100
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20101
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20102
0
            temp_buffer.resize(0);
20103
0
            for (ImGuiWindow* window : g.Windows)
20104
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20105
0
                    temp_buffer.push_back(window);
20106
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20107
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20108
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20109
0
            TreePop();
20110
0
        }
20111
20112
0
        TreePop();
20113
0
    }
20114
20115
    // DrawLists
20116
0
    int drawlist_count = 0;
20117
0
    for (ImGuiViewportP* viewport : g.Viewports)
20118
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20119
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20120
0
    {
20121
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20122
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20123
0
        for (ImGuiViewportP* viewport : g.Viewports)
20124
0
        {
20125
0
            bool viewport_has_drawlist = false;
20126
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20127
0
            {
20128
0
                if (!viewport_has_drawlist)
20129
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20130
0
                viewport_has_drawlist = true;
20131
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20132
0
            }
20133
0
        }
20134
0
        TreePop();
20135
0
    }
20136
20137
    // Viewports
20138
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20139
0
    {
20140
0
        cfg->HighlightMonitorIdx = -1;
20141
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20142
0
        SameLine();
20143
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20144
0
        if (open)
20145
0
        {
20146
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20147
0
            {
20148
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
20149
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
20150
0
                    i, mon.DpiScale * 100.0f,
20151
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
20152
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
20153
0
                if (IsItemHovered())
20154
0
                    cfg->HighlightMonitorIdx = i;
20155
0
            }
20156
0
            TreePop();
20157
0
        }
20158
20159
0
        SetNextItemOpen(true, ImGuiCond_Once);
20160
0
        if (TreeNode("Windows Minimap"))
20161
0
        {
20162
0
            RenderViewportsThumbnails();
20163
0
            TreePop();
20164
0
        }
20165
0
        cfg->HighlightViewportID = 0;
20166
20167
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20168
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20169
0
        {
20170
0
            static ImVector<ImGuiViewportP*> viewports;
20171
0
            viewports.resize(g.Viewports.Size);
20172
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20173
0
            if (viewports.Size > 1)
20174
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20175
0
            for (ImGuiViewportP* viewport : viewports)
20176
0
            {
20177
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20178
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20179
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20180
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20181
0
                if (IsItemHovered())
20182
0
                    cfg->HighlightViewportID = viewport->ID;
20183
0
            }
20184
0
            TreePop();
20185
0
        }
20186
20187
0
        for (ImGuiViewportP* viewport : g.Viewports)
20188
0
            DebugNodeViewport(viewport);
20189
0
        TreePop();
20190
0
    }
20191
20192
    // Details for Popups
20193
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20194
0
    {
20195
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20196
0
        {
20197
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20198
0
            ImGuiWindow* window = popup_data.Window;
20199
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20200
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20201
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20202
0
        }
20203
0
        TreePop();
20204
0
    }
20205
20206
    // Details for TabBars
20207
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20208
0
    {
20209
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20210
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20211
0
            {
20212
0
                PushID(tab_bar);
20213
0
                DebugNodeTabBar(tab_bar, "TabBar");
20214
0
                PopID();
20215
0
            }
20216
0
        TreePop();
20217
0
    }
20218
20219
    // Details for Tables
20220
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20221
0
    {
20222
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20223
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20224
0
                DebugNodeTable(table);
20225
0
        TreePop();
20226
0
    }
20227
20228
    // Details for Fonts
20229
0
    ImFontAtlas* atlas = g.IO.Fonts;
20230
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20231
0
    {
20232
0
        ShowFontAtlas(atlas);
20233
0
        TreePop();
20234
0
    }
20235
20236
    // Details for InputText
20237
0
    if (TreeNode("InputText"))
20238
0
    {
20239
0
        DebugNodeInputTextState(&g.InputTextState);
20240
0
        TreePop();
20241
0
    }
20242
20243
    // Details for TypingSelect
20244
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20245
0
    {
20246
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20247
0
        TreePop();
20248
0
    }
20249
20250
    // Details for Docking
20251
0
#ifdef IMGUI_HAS_DOCK
20252
0
    if (TreeNode("Docking"))
20253
0
    {
20254
0
        static bool root_nodes_only = true;
20255
0
        ImGuiDockContext* dc = &g.DockContext;
20256
0
        Checkbox("List root nodes", &root_nodes_only);
20257
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20258
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20259
0
        SameLine();
20260
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20261
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20262
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20263
0
                if (!root_nodes_only || node->IsRootNode())
20264
0
                    DebugNodeDockNode(node, "Node");
20265
0
        TreePop();
20266
0
    }
20267
0
#endif // #ifdef IMGUI_HAS_DOCK
20268
20269
    // Settings
20270
0
    if (TreeNode("Settings"))
20271
0
    {
20272
0
        if (SmallButton("Clear"))
20273
0
            ClearIniSettings();
20274
0
        SameLine();
20275
0
        if (SmallButton("Save to memory"))
20276
0
            SaveIniSettingsToMemory();
20277
0
        SameLine();
20278
0
        if (SmallButton("Save to disk"))
20279
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20280
0
        SameLine();
20281
0
        if (g.IO.IniFilename)
20282
0
            Text("\"%s\"", g.IO.IniFilename);
20283
0
        else
20284
0
            TextUnformatted("<NULL>");
20285
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20286
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20287
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20288
0
        {
20289
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20290
0
                BulletText("\"%s\"", handler.TypeName);
20291
0
            TreePop();
20292
0
        }
20293
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20294
0
        {
20295
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20296
0
                DebugNodeWindowSettings(settings);
20297
0
            TreePop();
20298
0
        }
20299
20300
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20301
0
        {
20302
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20303
0
                DebugNodeTableSettings(settings);
20304
0
            TreePop();
20305
0
        }
20306
20307
0
#ifdef IMGUI_HAS_DOCK
20308
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20309
0
        {
20310
0
            ImGuiDockContext* dc = &g.DockContext;
20311
0
            Text("In SettingsWindows:");
20312
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20313
0
                if (settings->DockId != 0)
20314
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20315
0
            Text("In SettingsNodes:");
20316
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20317
0
            {
20318
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20319
0
                const char* selected_tab_name = NULL;
20320
0
                if (settings->SelectedTabId)
20321
0
                {
20322
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20323
0
                        selected_tab_name = window->Name;
20324
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20325
0
                        selected_tab_name = window_settings->GetName();
20326
0
                }
20327
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20328
0
            }
20329
0
            TreePop();
20330
0
        }
20331
0
#endif // #ifdef IMGUI_HAS_DOCK
20332
20333
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20334
0
        {
20335
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20336
0
            TreePop();
20337
0
        }
20338
0
        TreePop();
20339
0
    }
20340
20341
    // Settings
20342
0
    if (TreeNode("Memory allocations"))
20343
0
    {
20344
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20345
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20346
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20347
0
        Text("Recent frames with allocations:");
20348
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20349
0
        for (int n = buf_size - 1; n >= 0; n--)
20350
0
        {
20351
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20352
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20353
0
        }
20354
0
        TreePop();
20355
0
    }
20356
20357
0
    if (TreeNode("Inputs"))
20358
0
    {
20359
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20360
0
        {
20361
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20362
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20363
0
            Indent();
20364
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20365
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20366
#else
20367
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20368
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20369
#endif
20370
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20371
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20372
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20373
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20374
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20375
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20376
0
            Unindent();
20377
0
        }
20378
20379
0
        Text("MOUSE STATE");
20380
0
        {
20381
0
            Indent();
20382
0
            if (IsMousePosValid())
20383
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20384
0
            else
20385
0
                Text("Mouse pos: <INVALID>");
20386
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20387
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20388
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20389
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20390
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20391
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20392
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20393
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20394
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20395
0
            Unindent();
20396
0
        }
20397
20398
0
        Text("MOUSE WHEELING");
20399
0
        {
20400
0
            Indent();
20401
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20402
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20403
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20404
0
            Unindent();
20405
0
        }
20406
20407
0
        Text("KEY OWNERS");
20408
0
        {
20409
0
            Indent();
20410
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20411
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20412
0
                {
20413
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20414
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
20415
0
                        continue;
20416
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20417
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20418
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20419
0
                }
20420
0
            EndChild();
20421
0
            Unindent();
20422
0
        }
20423
0
        Text("SHORTCUT ROUTING");
20424
0
        SameLine();
20425
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20426
0
        {
20427
0
            Indent();
20428
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20429
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20430
0
                {
20431
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20432
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20433
0
                    {
20434
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20435
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20436
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20437
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20438
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20439
0
                        {
20440
0
                            SameLine();
20441
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20442
0
                                g.DebugBreakInShortcutRouting = key_chord;
20443
0
                        }
20444
0
                        idx = routing_data->NextEntryIndex;
20445
0
                    }
20446
0
                }
20447
0
            EndChild();
20448
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20449
0
            Unindent();
20450
0
        }
20451
0
        TreePop();
20452
0
    }
20453
20454
0
    if (TreeNode("Internal state"))
20455
0
    {
20456
0
        Text("WINDOWING");
20457
0
        Indent();
20458
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20459
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20460
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20461
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20462
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20463
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20464
0
        Unindent();
20465
20466
0
        Text("ITEMS");
20467
0
        Indent();
20468
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20469
0
        DebugLocateItemOnHover(g.ActiveId);
20470
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20471
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20472
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20473
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20474
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20475
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20476
0
        Unindent();
20477
20478
0
        Text("NAV,FOCUS");
20479
0
        Indent();
20480
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20481
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20482
0
        DebugLocateItemOnHover(g.NavId);
20483
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20484
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20485
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20486
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20487
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20488
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20489
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20490
0
        Text("NavFocusRoute[] = ");
20491
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20492
0
        {
20493
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20494
0
            SameLine(0.0f, 0.0f);
20495
0
            Text("0x%08X/", focus_scope.ID);
20496
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20497
0
        }
20498
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20499
0
        Unindent();
20500
20501
0
        TreePop();
20502
0
    }
20503
20504
    // Overlay: Display windows Rectangles and Begin Order
20505
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20506
0
    {
20507
0
        for (ImGuiWindow* window : g.Windows)
20508
0
        {
20509
0
            if (!window->WasActive)
20510
0
                continue;
20511
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20512
0
            if (cfg->ShowWindowsRects)
20513
0
            {
20514
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20515
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20516
0
            }
20517
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20518
0
            {
20519
0
                char buf[32];
20520
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20521
0
                float font_size = GetFontSize();
20522
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20523
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20524
0
            }
20525
0
        }
20526
0
    }
20527
20528
    // Overlay: Display Tables Rectangles
20529
0
    if (cfg->ShowTablesRects)
20530
0
    {
20531
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20532
0
        {
20533
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20534
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20535
0
                continue;
20536
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20537
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20538
0
            {
20539
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20540
0
                {
20541
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20542
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20543
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20544
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20545
0
                }
20546
0
            }
20547
0
            else
20548
0
            {
20549
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20550
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20551
0
            }
20552
0
        }
20553
0
    }
20554
20555
0
#ifdef IMGUI_HAS_DOCK
20556
    // Overlay: Display Docking info
20557
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20558
0
    {
20559
0
        char buf[64] = "";
20560
0
        char* p = buf;
20561
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20562
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20563
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20564
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20565
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20566
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20567
0
        int depth = DockNodeGetDepth(node);
20568
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20569
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20570
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20571
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20572
0
    }
20573
0
#endif // #ifdef IMGUI_HAS_DOCK
20574
20575
0
    End();
20576
0
}
20577
20578
void ImGui::DebugBreakClearData()
20579
0
{
20580
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
20581
0
    ImGuiContext& g = *GImGui;
20582
0
    g.DebugBreakInWindow = 0;
20583
0
    g.DebugBreakInTable = 0;
20584
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
20585
0
}
20586
20587
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
20588
0
{
20589
0
    if (!BeginItemTooltip())
20590
0
        return;
20591
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
20592
0
    Separator();
20593
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
20594
0
    Separator();
20595
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
20596
0
    EndTooltip();
20597
0
}
20598
20599
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
20600
// In order to reduce interferences with the contents we are trying to debug into.
20601
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
20602
0
{
20603
0
    ImGuiWindow* window = GetCurrentWindow();
20604
0
    if (window->SkipItems)
20605
0
        return false;
20606
20607
0
    ImGuiContext& g = *GImGui;
20608
0
    const ImGuiID id = window->GetID(label);
20609
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
20610
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
20611
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
20612
20613
0
    const ImRect bb(pos, pos + size);
20614
0
    ItemSize(size, 0.0f);
20615
0
    if (!ItemAdd(bb, id))
20616
0
        return false;
20617
20618
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
20619
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
20620
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
20621
0
    DebugBreakButtonTooltip(false, description_of_location);
20622
20623
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
20624
0
    ImVec4 hsv;
20625
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
20626
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
20627
20628
0
    RenderNavHighlight(bb, id);
20629
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
20630
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
20631
20632
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
20633
0
    return pressed;
20634
0
}
20635
20636
// [DEBUG] Display contents of Columns
20637
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20638
0
{
20639
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20640
0
        return;
20641
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20642
0
    for (ImGuiOldColumnData& column : columns->Columns)
20643
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20644
0
    TreePop();
20645
0
}
20646
20647
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20648
0
{
20649
0
    using namespace ImGui;
20650
0
    PushID(label);
20651
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20652
0
    Text("%s:", label);
20653
0
    if (!enabled)
20654
0
        BeginDisabled();
20655
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20656
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20657
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20658
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20659
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20660
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20661
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20662
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
20663
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20664
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20665
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20666
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20667
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20668
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20669
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20670
0
    if (!enabled)
20671
0
        EndDisabled();
20672
0
    PopStyleVar();
20673
0
    PopID();
20674
0
}
20675
20676
// [DEBUG] Display contents of ImDockNode
20677
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20678
0
{
20679
0
    ImGuiContext& g = *GImGui;
20680
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20681
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
20682
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20683
0
    bool open;
20684
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20685
0
    if (node->Windows.Size > 0)
20686
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20687
0
    else
20688
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20689
0
    if (!is_alive) { PopStyleColor(); }
20690
0
    if (is_active && IsItemHovered())
20691
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20692
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20693
0
    if (open)
20694
0
    {
20695
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20696
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20697
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20698
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20699
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
20700
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20701
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20702
0
        BulletText("Misc:%s%s%s%s%s%s%s",
20703
0
            node->IsDockSpace() ? " IsDockSpace" : "",
20704
0
            node->IsCentralNode() ? " IsCentralNode" : "",
20705
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20706
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20707
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20708
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20709
0
        {
20710
0
            if (BeginTable("flags", 4))
20711
0
            {
20712
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20713
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20714
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20715
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20716
0
                EndTable();
20717
0
            }
20718
0
            TreePop();
20719
0
        }
20720
0
        if (node->ParentNode)
20721
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
20722
0
        if (node->ChildNodes[0])
20723
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20724
0
        if (node->ChildNodes[1])
20725
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20726
0
        if (node->TabBar)
20727
0
            DebugNodeTabBar(node->TabBar, "TabBar");
20728
0
        DebugNodeWindowsList(&node->Windows, "Windows");
20729
20730
0
        TreePop();
20731
0
    }
20732
0
}
20733
20734
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
20735
0
{
20736
0
    union { void* ptr; int integer; } tex_id_opaque;
20737
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
20738
0
    if (sizeof(tex_id) >= sizeof(void*))
20739
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
20740
0
    else
20741
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
20742
0
}
20743
20744
// [DEBUG] Display contents of ImDrawList
20745
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20746
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20747
0
{
20748
0
    ImGuiContext& g = *GImGui;
20749
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20750
0
    int cmd_count = draw_list->CmdBuffer.Size;
20751
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20752
0
        cmd_count--;
20753
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20754
0
    if (draw_list == GetWindowDrawList())
20755
0
    {
20756
0
        SameLine();
20757
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20758
0
        if (node_open)
20759
0
            TreePop();
20760
0
        return;
20761
0
    }
20762
20763
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20764
0
    if (window && IsItemHovered() && fg_draw_list)
20765
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20766
0
    if (!node_open)
20767
0
        return;
20768
20769
0
    if (window && !window->WasActive)
20770
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20771
20772
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20773
0
    {
20774
0
        if (pcmd->UserCallback)
20775
0
        {
20776
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20777
0
            continue;
20778
0
        }
20779
20780
0
        char texid_desc[20];
20781
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
20782
0
        char buf[300];
20783
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20784
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20785
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20786
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20787
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20788
0
        if (!pcmd_node_open)
20789
0
            continue;
20790
20791
        // Calculate approximate coverage area (touched pixel count)
20792
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20793
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20794
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20795
0
        float total_area = 0.0f;
20796
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20797
0
        {
20798
0
            ImVec2 triangle[3];
20799
0
            for (int n = 0; n < 3; n++, idx_n++)
20800
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20801
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20802
0
        }
20803
20804
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20805
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20806
0
        Selectable(buf);
20807
0
        if (IsItemHovered() && fg_draw_list)
20808
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20809
20810
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20811
0
        ImGuiListClipper clipper;
20812
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20813
0
        while (clipper.Step())
20814
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20815
0
            {
20816
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20817
0
                ImVec2 triangle[3];
20818
0
                for (int n = 0; n < 3; n++, idx_i++)
20819
0
                {
20820
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20821
0
                    triangle[n] = v.pos;
20822
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20823
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20824
0
                }
20825
20826
0
                Selectable(buf, false);
20827
0
                if (fg_draw_list && IsItemHovered())
20828
0
                {
20829
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20830
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20831
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20832
0
                    fg_draw_list->Flags = backup_flags;
20833
0
                }
20834
0
            }
20835
0
        TreePop();
20836
0
    }
20837
0
    TreePop();
20838
0
}
20839
20840
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20841
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20842
0
{
20843
0
    IM_ASSERT(show_mesh || show_aabb);
20844
20845
    // Draw wire-frame version of all triangles
20846
0
    ImRect clip_rect = draw_cmd->ClipRect;
20847
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20848
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20849
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20850
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20851
0
    {
20852
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20853
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20854
20855
0
        ImVec2 triangle[3];
20856
0
        for (int n = 0; n < 3; n++, idx_n++)
20857
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20858
0
        if (show_mesh)
20859
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20860
0
    }
20861
    // Draw bounding boxes
20862
0
    if (show_aabb)
20863
0
    {
20864
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20865
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20866
0
    }
20867
0
    out_draw_list->Flags = backup_flags;
20868
0
}
20869
20870
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20871
void ImGui::DebugNodeFont(ImFont* font)
20872
0
{
20873
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20874
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20875
0
    SameLine();
20876
0
    if (SmallButton("Set as default"))
20877
0
        GetIO().FontDefault = font;
20878
0
    if (!opened)
20879
0
        return;
20880
20881
    // Display preview text
20882
0
    PushFont(font);
20883
0
    Text("The quick brown fox jumps over the lazy dog");
20884
0
    PopFont();
20885
20886
    // Display details
20887
0
    SetNextItemWidth(GetFontSize() * 8);
20888
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20889
0
    SameLine(); MetricsHelpMarker(
20890
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
20891
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20892
0
        "You may oversample them to get some flexibility with scaling. "
20893
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20894
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20895
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20896
0
    char c_str[5];
20897
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20898
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20899
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20900
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20901
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20902
0
        if (font->ConfigData)
20903
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20904
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20905
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20906
20907
    // Display all glyphs of the fonts in separate pages of 256 characters
20908
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20909
0
    {
20910
0
        ImDrawList* draw_list = GetWindowDrawList();
20911
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20912
0
        const float cell_size = font->FontSize * 1;
20913
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20914
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20915
0
        {
20916
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20917
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20918
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20919
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20920
0
            {
20921
0
                base += 4096 - 256;
20922
0
                continue;
20923
0
            }
20924
20925
0
            int count = 0;
20926
0
            for (unsigned int n = 0; n < 256; n++)
20927
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20928
0
                    count++;
20929
0
            if (count <= 0)
20930
0
                continue;
20931
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20932
0
                continue;
20933
20934
            // Draw a 16x16 grid of glyphs
20935
0
            ImVec2 base_pos = GetCursorScreenPos();
20936
0
            for (unsigned int n = 0; n < 256; n++)
20937
0
            {
20938
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20939
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20940
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20941
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20942
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20943
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20944
0
                if (!glyph)
20945
0
                    continue;
20946
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20947
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20948
0
                {
20949
0
                    DebugNodeFontGlyph(font, glyph);
20950
0
                    EndTooltip();
20951
0
                }
20952
0
            }
20953
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20954
0
            TreePop();
20955
0
        }
20956
0
        TreePop();
20957
0
    }
20958
0
    TreePop();
20959
0
}
20960
20961
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20962
0
{
20963
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20964
0
    Separator();
20965
0
    Text("Visible: %d", glyph->Visible);
20966
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20967
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20968
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20969
0
}
20970
20971
// [DEBUG] Display contents of ImGuiStorage
20972
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20973
0
{
20974
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20975
0
        return;
20976
0
    for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20977
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20978
0
    TreePop();
20979
0
}
20980
20981
// [DEBUG] Display contents of ImGuiTabBar
20982
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20983
0
{
20984
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20985
0
    char buf[256];
20986
0
    char* p = buf;
20987
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20988
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20989
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20990
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20991
0
    {
20992
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20993
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20994
0
    }
20995
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20996
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20997
0
    bool open = TreeNode(label, "%s", buf);
20998
0
    if (!is_active) { PopStyleColor(); }
20999
0
    if (is_active && IsItemHovered())
21000
0
    {
21001
0
        ImDrawList* draw_list = GetForegroundDrawList();
21002
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
21003
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21004
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21005
0
    }
21006
0
    if (open)
21007
0
    {
21008
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
21009
0
        {
21010
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21011
0
            PushID(tab);
21012
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
21013
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
21014
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
21015
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
21016
0
            PopID();
21017
0
        }
21018
0
        TreePop();
21019
0
    }
21020
0
}
21021
21022
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
21023
0
{
21024
0
    ImGuiContext& g = *GImGui;
21025
0
    SetNextItemOpen(true, ImGuiCond_Once);
21026
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21027
0
    if (IsItemHovered())
21028
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21029
0
    if (open)
21030
0
    {
21031
0
        ImGuiWindowFlags flags = viewport->Flags;
21032
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21033
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21034
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21035
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21036
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21037
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21038
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21039
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21040
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21041
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21042
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21043
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21044
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21045
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21046
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21047
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21048
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21049
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21050
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21051
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21052
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21053
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21054
0
        TreePop();
21055
0
    }
21056
0
}
21057
21058
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21059
0
{
21060
0
    if (window == NULL)
21061
0
    {
21062
0
        BulletText("%s: NULL", label);
21063
0
        return;
21064
0
    }
21065
21066
0
    ImGuiContext& g = *GImGui;
21067
0
    const bool is_active = window->WasActive;
21068
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21069
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21070
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21071
0
    if (!is_active) { PopStyleColor(); }
21072
0
    if (IsItemHovered() && is_active)
21073
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21074
0
    if (!open)
21075
0
        return;
21076
21077
0
    if (window->MemoryCompacted)
21078
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21079
21080
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21081
0
        g.DebugBreakInWindow = window->ID;
21082
21083
0
    ImGuiWindowFlags flags = window->Flags;
21084
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21085
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21086
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21087
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21088
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21089
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21090
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21091
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21092
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21093
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21094
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21095
0
    {
21096
0
        ImRect r = window->NavRectRel[layer];
21097
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21098
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21099
0
        else
21100
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21101
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21102
0
    }
21103
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21104
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21105
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21106
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21107
21108
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21109
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21110
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21111
0
    if (window->DockNode || window->DockNodeAsHost)
21112
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21113
21114
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21115
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21116
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21117
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21118
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21119
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21120
0
    {
21121
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21122
0
            DebugNodeColumns(&columns);
21123
0
        TreePop();
21124
0
    }
21125
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21126
0
    TreePop();
21127
0
}
21128
21129
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21130
0
{
21131
0
    if (settings->WantDelete)
21132
0
        BeginDisabled();
21133
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21134
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21135
0
    if (settings->WantDelete)
21136
0
        EndDisabled();
21137
0
}
21138
21139
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21140
0
{
21141
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21142
0
        return;
21143
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21144
0
    {
21145
0
        PushID((*windows)[i]);
21146
0
        DebugNodeWindow((*windows)[i], "Window");
21147
0
        PopID();
21148
0
    }
21149
0
    TreePop();
21150
0
}
21151
21152
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21153
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21154
0
{
21155
0
    for (int i = 0; i < windows_size; i++)
21156
0
    {
21157
0
        ImGuiWindow* window = windows[i];
21158
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21159
0
            continue;
21160
0
        char buf[20];
21161
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21162
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21163
0
        DebugNodeWindow(window, buf);
21164
0
        Indent();
21165
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21166
0
        Unindent();
21167
0
    }
21168
0
}
21169
21170
//-----------------------------------------------------------------------------
21171
// [SECTION] DEBUG LOG WINDOW
21172
//-----------------------------------------------------------------------------
21173
21174
void ImGui::DebugLog(const char* fmt, ...)
21175
0
{
21176
0
    va_list args;
21177
0
    va_start(args, fmt);
21178
0
    DebugLogV(fmt, args);
21179
0
    va_end(args);
21180
0
}
21181
21182
void ImGui::DebugLogV(const char* fmt, va_list args)
21183
0
{
21184
0
    ImGuiContext& g = *GImGui;
21185
0
    const int old_size = g.DebugLogBuf.size();
21186
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21187
0
    g.DebugLogBuf.appendfv(fmt, args);
21188
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21189
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21190
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21191
#ifdef IMGUI_ENABLE_TEST_ENGINE
21192
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21193
        IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
21194
#endif
21195
0
}
21196
21197
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21198
static void SameLineOrWrap(const ImVec2& size)
21199
0
{
21200
0
    ImGuiContext& g = *GImGui;
21201
0
    ImGuiWindow* window = g.CurrentWindow;
21202
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21203
0
    if (window->ClipRect.Contains(ImRect(pos, pos + size)))
21204
0
        ImGui::SameLine();
21205
0
}
21206
21207
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21208
0
{
21209
0
    ImGuiContext& g = *GImGui;
21210
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21211
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21212
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21213
0
    {
21214
0
        g.DebugLogAutoDisableFrames = 2;
21215
0
        g.DebugLogAutoDisableFlags |= flags;
21216
0
    }
21217
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21218
0
}
21219
21220
void ImGui::ShowDebugLogWindow(bool* p_open)
21221
0
{
21222
0
    ImGuiContext& g = *GImGui;
21223
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21224
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21225
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21226
0
    {
21227
0
        End();
21228
0
        return;
21229
0
    }
21230
21231
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21232
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21233
0
    SetItemTooltip("(except InputRouting which is spammy)");
21234
21235
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21236
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21237
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21238
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21239
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21240
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21241
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21242
    //ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21243
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21244
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21245
21246
0
    if (SmallButton("Clear"))
21247
0
    {
21248
0
        g.DebugLogBuf.clear();
21249
0
        g.DebugLogIndex.clear();
21250
0
    }
21251
0
    SameLine();
21252
0
    if (SmallButton("Copy"))
21253
0
        SetClipboardText(g.DebugLogBuf.c_str());
21254
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21255
21256
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21257
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21258
21259
0
    ImGuiListClipper clipper;
21260
0
    clipper.Begin(g.DebugLogIndex.size());
21261
0
    while (clipper.Step())
21262
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21263
0
        {
21264
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
21265
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
21266
0
            TextUnformatted(line_begin, line_end); // Display line
21267
0
            ImRect text_rect = g.LastItemData.Rect;
21268
0
            if (IsItemHovered())
21269
0
                for (const char* p = line_begin; p <= line_end - 10; p++) // Search for 0x???????? identifiers
21270
0
                {
21271
0
                    ImGuiID id = 0;
21272
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
21273
0
                        continue;
21274
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
21275
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
21276
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21277
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21278
0
                        DebugLocateItemOnHover(id);
21279
0
                    p += 10;
21280
0
                }
21281
0
        }
21282
0
    g.DebugLogFlags = backup_log_flags;
21283
0
    if (GetScrollY() >= GetScrollMaxY())
21284
0
        SetScrollHereY(1.0f);
21285
0
    EndChild();
21286
21287
0
    End();
21288
0
}
21289
21290
//-----------------------------------------------------------------------------
21291
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21292
//-----------------------------------------------------------------------------
21293
21294
// Draw a small cross at current CursorPos in current window's DrawList
21295
void ImGui::DebugDrawCursorPos(ImU32 col)
21296
0
{
21297
0
    ImGuiContext& g = *GImGui;
21298
0
    ImGuiWindow* window = g.CurrentWindow;
21299
0
    ImVec2 pos = window->DC.CursorPos;
21300
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21301
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21302
0
}
21303
21304
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21305
void ImGui::DebugDrawLineExtents(ImU32 col)
21306
0
{
21307
0
    ImGuiContext& g = *GImGui;
21308
0
    ImGuiWindow* window = g.CurrentWindow;
21309
0
    float curr_x = window->DC.CursorPos.x;
21310
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21311
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21312
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21313
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21314
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21315
0
}
21316
21317
// Draw last item rect in ForegroundDrawList (so it is always visible)
21318
void ImGui::DebugDrawItemRect(ImU32 col)
21319
0
{
21320
0
    ImGuiContext& g = *GImGui;
21321
0
    ImGuiWindow* window = g.CurrentWindow;
21322
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21323
0
}
21324
21325
// [DEBUG] Locate item position/rectangle given an ID.
21326
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21327
21328
void ImGui::DebugLocateItem(ImGuiID target_id)
21329
0
{
21330
0
    ImGuiContext& g = *GImGui;
21331
0
    g.DebugLocateId = target_id;
21332
0
    g.DebugLocateFrames = 2;
21333
0
    g.DebugBreakInLocateId = false;
21334
0
}
21335
21336
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21337
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21338
0
{
21339
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21340
0
        return;
21341
0
    ImGuiContext& g = *GImGui;
21342
0
    DebugLocateItem(target_id);
21343
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21344
21345
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21346
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21347
0
    {
21348
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21349
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21350
0
            g.DebugBreakInLocateId = true;
21351
0
    }
21352
0
}
21353
21354
void ImGui::DebugLocateItemResolveWithLastItem()
21355
0
{
21356
0
    ImGuiContext& g = *GImGui;
21357
21358
    // [DEBUG] Debug break requested by user
21359
0
    if (g.DebugBreakInLocateId)
21360
0
        IM_DEBUG_BREAK();
21361
21362
0
    ImGuiLastItemData item_data = g.LastItemData;
21363
0
    g.DebugLocateId = 0;
21364
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21365
0
    ImRect r = item_data.Rect;
21366
0
    r.Expand(3.0f);
21367
0
    ImVec2 p1 = g.IO.MousePos;
21368
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21369
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21370
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21371
0
}
21372
21373
void ImGui::DebugStartItemPicker()
21374
0
{
21375
0
    ImGuiContext& g = *GImGui;
21376
0
    g.DebugItemPickerActive = true;
21377
0
}
21378
21379
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21380
void ImGui::UpdateDebugToolItemPicker()
21381
0
{
21382
0
    ImGuiContext& g = *GImGui;
21383
0
    g.DebugItemPickerBreakId = 0;
21384
0
    if (!g.DebugItemPickerActive)
21385
0
        return;
21386
21387
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21388
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21389
0
    if (IsKeyPressed(ImGuiKey_Escape))
21390
0
        g.DebugItemPickerActive = false;
21391
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21392
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21393
0
    {
21394
0
        g.DebugItemPickerBreakId = hovered_id;
21395
0
        g.DebugItemPickerActive = false;
21396
0
    }
21397
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21398
0
        if (change_mapping && IsMouseClicked(mouse_button))
21399
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21400
0
    SetNextWindowBgAlpha(0.70f);
21401
0
    if (!BeginTooltip())
21402
0
        return;
21403
0
    Text("HoveredId: 0x%08X", hovered_id);
21404
0
    Text("Press ESC to abort picking.");
21405
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21406
0
    if (change_mapping)
21407
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21408
0
    else
21409
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21410
0
    EndTooltip();
21411
0
}
21412
21413
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21414
void ImGui::UpdateDebugToolStackQueries()
21415
0
{
21416
0
    ImGuiContext& g = *GImGui;
21417
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21418
21419
    // Clear hook when id stack tool is not visible
21420
0
    g.DebugHookIdInfo = 0;
21421
0
    if (g.FrameCount != tool->LastActiveFrame + 1)
21422
0
        return;
21423
21424
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21425
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21426
0
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21427
0
    if (tool->QueryId != query_id)
21428
0
    {
21429
0
        tool->QueryId = query_id;
21430
0
        tool->StackLevel = -1;
21431
0
        tool->Results.resize(0);
21432
0
    }
21433
0
    if (query_id == 0)
21434
0
        return;
21435
21436
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21437
0
    int stack_level = tool->StackLevel;
21438
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21439
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21440
0
            tool->StackLevel++;
21441
21442
    // Update hook
21443
0
    stack_level = tool->StackLevel;
21444
0
    if (stack_level == -1)
21445
0
        g.DebugHookIdInfo = query_id;
21446
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21447
0
    {
21448
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21449
0
        tool->Results[stack_level].QueryFrameCount++;
21450
0
    }
21451
0
}
21452
21453
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21454
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21455
0
{
21456
0
    ImGuiContext& g = *GImGui;
21457
0
    ImGuiWindow* window = g.CurrentWindow;
21458
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21459
21460
    // Step 0: stack query
21461
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21462
0
    if (tool->StackLevel == -1)
21463
0
    {
21464
0
        tool->StackLevel++;
21465
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21466
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21467
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21468
0
        return;
21469
0
    }
21470
21471
    // Step 1+: query for individual level
21472
0
    IM_ASSERT(tool->StackLevel >= 0);
21473
0
    if (tool->StackLevel != window->IDStack.Size)
21474
0
        return;
21475
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21476
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21477
21478
0
    switch (data_type)
21479
0
    {
21480
0
    case ImGuiDataType_S32:
21481
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21482
0
        break;
21483
0
    case ImGuiDataType_String:
21484
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21485
0
        break;
21486
0
    case ImGuiDataType_Pointer:
21487
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21488
0
        break;
21489
0
    case ImGuiDataType_ID:
21490
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21491
0
            return;
21492
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21493
0
        break;
21494
0
    default:
21495
0
        IM_ASSERT(0);
21496
0
    }
21497
0
    info->QuerySuccess = true;
21498
0
    info->DataType = data_type;
21499
0
}
21500
21501
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21502
0
{
21503
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
21504
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21505
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21506
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21507
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21508
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21509
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21510
0
        return (*buf = 0);
21511
#ifdef IMGUI_ENABLE_TEST_ENGINE
21512
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
21513
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
21514
#endif
21515
0
    return ImFormatString(buf, buf_size, "???");
21516
0
}
21517
21518
// ID Stack Tool: Display UI
21519
void ImGui::ShowIDStackToolWindow(bool* p_open)
21520
0
{
21521
0
    ImGuiContext& g = *GImGui;
21522
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21523
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
21524
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
21525
0
    {
21526
0
        End();
21527
0
        return;
21528
0
    }
21529
21530
    // Display hovered/active status
21531
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21532
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21533
0
    const ImGuiID active_id = g.ActiveId;
21534
#ifdef IMGUI_ENABLE_TEST_ENGINE
21535
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
21536
#else
21537
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
21538
0
#endif
21539
0
    SameLine();
21540
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
21541
21542
    // CTRL+C to copy path
21543
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
21544
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
21545
0
    SameLine();
21546
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
21547
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, ImGuiInputFlags_RouteGlobal))
21548
0
    {
21549
0
        tool->CopyToClipboardLastTime = (float)g.Time;
21550
0
        char* p = g.TempBuffer.Data;
21551
0
        char* p_end = p + g.TempBuffer.Size;
21552
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
21553
0
        {
21554
0
            *p++ = '/';
21555
0
            char level_desc[256];
21556
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
21557
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
21558
0
            {
21559
0
                if (level_desc[n] == '/')
21560
0
                    *p++ = '\\';
21561
0
                *p++ = level_desc[n];
21562
0
            }
21563
0
        }
21564
0
        *p = '\0';
21565
0
        SetClipboardText(g.TempBuffer.Data);
21566
0
    }
21567
21568
    // Display decorated stack
21569
0
    tool->LastActiveFrame = g.FrameCount;
21570
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
21571
0
    {
21572
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
21573
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
21574
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
21575
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21576
0
        TableHeadersRow();
21577
0
        for (int n = 0; n < tool->Results.Size; n++)
21578
0
        {
21579
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
21580
0
            TableNextColumn();
21581
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21582
0
            TableNextColumn();
21583
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21584
0
            TextUnformatted(g.TempBuffer.Data);
21585
0
            TableNextColumn();
21586
0
            Text("0x%08X", info->ID);
21587
0
            if (n == tool->Results.Size - 1)
21588
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
21589
0
        }
21590
0
        EndTable();
21591
0
    }
21592
0
    End();
21593
0
}
21594
21595
#else
21596
21597
void ImGui::ShowMetricsWindow(bool*) {}
21598
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21599
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21600
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21601
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21602
void ImGui::DebugNodeFont(ImFont*) {}
21603
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21604
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21605
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21606
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21607
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21608
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21609
21610
void ImGui::DebugLog(const char*, ...) {}
21611
void ImGui::DebugLogV(const char*, va_list) {}
21612
void ImGui::ShowDebugLogWindow(bool*) {}
21613
void ImGui::ShowIDStackToolWindow(bool*) {}
21614
void ImGui::DebugStartItemPicker() {}
21615
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21616
21617
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21618
21619
//-----------------------------------------------------------------------------
21620
21621
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21622
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21623
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21624
#include "imgui_user.inl"
21625
#endif
21626
21627
//-----------------------------------------------------------------------------
21628
21629
#endif // #ifndef IMGUI_DISABLE